0

Supposed that I have an array like matrix using numpy like this.

import numpy as np

a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]])

I want to change the [13, 14, 15, 16] into the first position so it will become something like this

array([[ 13, 14, 15, 16],
       [ 1,  2,  3,  4 ],
       [ 5,  6,  7,  8 ],
       [ 9, 10, 11, 12 ],
       [ 17, 18, 19, 20])

how can I do it? thanks

1

2 Answers 2

2

You can re-arrange the array with the row indices:

import numpy as np

a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]])

b = a[[3,0,1,2,4],:]

print(b)

The output is:

[[13 14 15 16]
 [ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [17 18 19 20]]
Sign up to request clarification or add additional context in comments.

Comments

1

Use np.delete and np.concatenate:

b = np.concatenate([a[[-2]], np.delete(a, -2, axis=0)])
print(b)

# Output
[[13 14 15 16]
 [ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [17 18 19 20]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.