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

岁酱吖の 提交于 2021-01-20 23:40:34

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/54069863/swap-two-rows-in-a-numpy-array-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!