Swap two rows in a numpy array in python

Manish picture Manish · Jan 7, 2019 · Viewed 31.3k times · Source

How to swap xth and yth rows of the 2-D NumPy array? x & y are inputs provided by the user. Lets say x = 0 & y =2 , and the input array is as below:

a = [[4 3 1] 
         [5 7 0] 
         [9 9 3] 
         [8 2 4]] 
Expected Output : 
[[9 9 3] 
 [5 7 0] 
 [4 3 1] 
 [8 2 4]] 

I tried multiple things, but did not get the expected result. this is what i tried:

a[x],a[y]= a[y],a[x]

output i got is:
[[9 9 3]
 [5 7 0]
 [9 9 3]
 [8 2 4]]

Please suggest what is wrong in my solution.

Answer

Chris picture Chris · Jan 7, 2019

Put the index as a whole:

a[[x, y]] = a[[y, x]]

With your example:

a = np.array([[4,3,1], [5,7,0], [9,9,3], [8,2,4]])

a 
# array([[4, 3, 1],
#        [5, 7, 0],
#        [9, 9, 3],
#        [8, 2, 4]])

a[[0, 2]] = a[[2, 0]]
a
# array([[9, 9, 3],
#       [5, 7, 0],
#       [4, 3, 1],
#       [8, 2, 4]])