Home > database >  Change numpy array element position in python
Change numpy array element position in python

Time:01-26

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

CodePudding user response:

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]]

CodePudding user response:

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]]
  •  Tags:  
  • Related