Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap two rows in a numpy array in python [duplicate]

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.

like image 376
Manish Avatar asked Jan 07 '19 07:01

Manish


People also ask

How do you switch rows in Python?

Use the T attribute or the transpose() method to swap (= transpose) the rows and columns of pandas. DataFrame . Neither method changes the original object but returns a new object with the rows and columns swapped (= transposed object).

How do I swap columns and rows in NumPy array?

To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.


Video Answer


1 Answers

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]])
like image 145
Chris Avatar answered Oct 17 '22 00:10

Chris