在python中的numpy数组中交换两行 [英] Swap two rows in a numpy array in python

查看:126
本文介绍了在python中的numpy数组中交换两行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何交换二维NumPy数组的第x和yth行?x&y是用户提供的输入.假设x = 0&y = 2,输入数组如下:

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.

推荐答案

放置整个索引:

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

以您的示例为例:

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

这篇关于在python中的numpy数组中交换两行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆