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.
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).
To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With