在numpy数组中交换列? [英] Swapping columns in a numpy array?

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

问题描述

from numpy import *
def swap_columns(my_array, col1, col2):
    temp = my_array[:,col1]
    my_array[:,col1] = my_array[:,col2]
    my_array[:,col2] = temp

然后

swap_columns(data, 0, 1)

不起作用.但是,直接调用代码

Doesn't work. However, calling the code directly

temp = my_array[:,0]
my_array[:,0] = my_array[:,1]
my_array[:,1] = temp

是.为什么会发生这种情况,我该如何解决?错误显示"IndexError:0维数组只能使用单个()或新轴列表(和单个...)作为索引",这意味着参数不是整数吗?我已经尝试过将cols转换为int,但是没有解决.

Does. Why is this happening and how can I fix it? The Error says "IndexError: 0-d arrays can only use a single () or a list of newaxes (and a single ...) as an index", which implies the arguments aren't ints? I already tried converting the cols to int but that didn't solve it.

推荐答案

这里有两个问题.首先是您传递给函数的data显然不是二维NumPy数组-至少这就是错误消息所说的内容.

There are two issues here. The first is that the data you pass to your function apparently isn't a two-dimensional NumPy array -- at least this is what the error message says.

第二个问题是该代码无法满足您的期望:

The second issue is that the code does not do what you expect:

my_array = numpy.arange(9).reshape(3, 3)
# array([[0, 1, 2],
#        [3, 4, 5],
#        [6, 7, 8]])
temp = my_array[:, 0]
my_array[:, 0] = my_array[:, 1]
my_array[:, 1] = temp
# array([[1, 1, 2],
#        [4, 4, 5],
#        [7, 7, 8]])

问题在于Numpy 基本切片不会创建实际数据的副本,而是创建相同数据的视图.要使此工作有效,您必须显式复制

The problem is that Numpy basic slicing does not create copies of the actual data, but rather a view to the same data. To make this work, you either have to copy explicitly

temp = numpy.copy(my_array[:, 0])
my_array[:, 0] = my_array[:, 1]
my_array[:, 1] = temp

或使用高级切片

or use advanced slicing

my_array[:,[0, 1]] = my_array[:,[1, 0]]

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

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