Python 交换numpy数组中的列?
然后 不起作用。但是,直接调用代码Python 交换numpy数组中的列?,python,numpy,Python,Numpy,然后 不起作用。但是,直接调用代码 swap_columns(data, 0, 1) 是的。为什么会发生这种情况?我如何修复它?错误表示“IndexError:0-d数组只能使用单个()或一个新轴列表(以及单个…)作为索引”,这意味着参数不是int?我已经尝试过将cols转换为int,但没有解决它。这里有两个问题。首先,传递给函数的数据显然不是二维NumPy数组——至少错误消息是这样说的 第二个问题是,代码没有达到您期望的效果: temp = my_array[:,0] my_array[:,
swap_columns(data, 0, 1)
是的。为什么会发生这种情况?我如何修复它?错误表示“IndexError:0-d数组只能使用单个()或一个新轴列表(以及单个…)作为索引”,这意味着参数不是int?我已经尝试过将cols转换为int,但没有解决它。这里有两个问题。首先,传递给函数的
数据显然不是二维NumPy数组——至少错误消息是这样说的
第二个问题是,代码没有达到您期望的效果:
temp = my_array[:,0]
my_array[:,0] = my_array[:,1]
my_array[:,1] = temp
问题在于Numpy不创建实际数据的副本,而是创建相同数据的视图。要使其工作,您必须显式复制
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]])
或使用
基于@Sven的答案:
my_array[:,[0, 1]] = my_array[:,[1, 0]]
我发现以下各项最快:
import numpy as np
my_array = np.arange(9).reshape(3, 3)
print my_array
[[0 1 2]
[3 4 5]
[6 7 8]]
def swap_cols(arr, frm, to):
arr[:,[frm, to]] = arr[:,[to, frm]]
swap_cols(my_array, 0, 1)
print my_array
[[1 0 2]
[4 3 5]
[7 6 8]]
def swap_rows(arr, frm, to):
arr[[frm, to],:] = arr[[to, frm],:]
my_array = np.arange(9).reshape(3, 3)
swap_rows(my_array, 0, 2)
print my_array
[[6 7 8]
[3 4 5]
[0 1 2]]
时间分析:
my_array[:, 0], my_array[:, 1] = my_array[:, 1], my_array[:, 0].copy()
详情如下:
import numpy as np
my_array = np.arange(900).reshape(30, 30)
高级切片时间为:
%timeit my_array[:, 0], my_array[:, 1] = my_array[:, 1], my_array[:, 0].copy()
The slowest run took 15.05 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 1.72 µs per loop
在NumPy中交换列的一种优雅方式类似于交换两个变量
在Python中,例如:x,y=y,x
%timeit my_array[:,[0, 1]] = my_array[:,[1, 0]]
The slowest run took 7.38 times longer than the fastest. This could mean that an intermediate result is being cached
100000 loops, best of 3: 6.9 µs per loop
假设您有一个numpy数组a
,如下所示:
i, j = 0, 1
A.T[[i, j]] = A.T[[j, i]] # swap the columns i and j
A.T[[0,1]]=A.T[[1,0]]
将交换前两列:
array([[ 0., -1., 0., 0.],
[ 0., 1., 1., 1.],
[ 0., 0., -1., 0.],
[ 0., 0., 0., -1.]])
Upvote对于copy()部分,我的代码中缺少了这一点。高级切片似乎也不会复制数据。@MateenUlhaq请放心,它会的。看看链接的文档,或者自己试试。确实非常优雅和聪明。谢谢
i, j = 0, 1
A.T[[i, j]] = A.T[[j, i]] # swap the columns i and j
array([[ 0., -1., 0., 0.],
[ 0., 1., 1., 1.],
[ 0., 0., -1., 0.],
[ 0., 0., 0., -1.]])
array([[-1., 0., 0., 0.],
[ 1., 0., 1., 1.],
[ 0., 0., -1., 0.],
[ 0., 0., 0., -1.]])