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

RamaH
  • 43
  • 4

2 Answers2

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]]
hesham_EE
  • 1,125
  • 13
  • 24
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]]
Corralien
  • 109,409
  • 8
  • 28
  • 52