简体   繁体   English

交换numpy数组中的列?

[英]Swapping columns in a numpy array?

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

Then然后

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

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?错误说“IndexError: 0-d arrays can only use a single () or a list of newaxes (and a single ...) as an index”,这意味着参数不是整数? I already tried converting the cols to int but that didn't solve it.我已经尝试将 cols 转换为 int 但这并没有解决它。

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.首先是您传递给函数的data显然不是二维 NumPy 数组——至少这是错误消息所说的。

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

The problem is that Numpy basic slicing does not create copies of the actual data, but rather a view to the same data.问题是 Numpy 基本切片不会创建实际数据的副本,而是创建相同数据的视图。 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]]

I find the following the fastest:我发现以下最快:

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

Time analysis of:时间分析:

import numpy as np
my_array = np.arange(900).reshape(30, 30)

is as follows:如下:

%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

The advanced slicing times are:高级切片时间为:

%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

Building up on @Sven's answer:以@Sven 的回答为基础:

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

An elegant way to swap the columns in NumPy is analogy to swapping two variables in Python like so: x, y = y, x .在 NumPy 中交换列的一种优雅方式类似于在 Python 中交换两个变量,如下所示: x, y = y, x

i, j = 0, 1
A.T[[i, j]] = A.T[[j, i]]  # swap the columns i and j

Suppose you have a numpy array A like this:假设你有一个像这样的 numpy 数组A

array([[ 0., -1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.],
       [ 0.,  0., -1.,  0.],
       [ 0.,  0.,  0., -1.]])

AT[[0, 1]] = AT[[1, 0]] will swap the first two columns: AT[[0, 1]] = AT[[1, 0]]将交换前两列:

array([[-1.,  0.,  0.,  0.],
       [ 1.,  0.,  1.,  1.],
       [ 0.,  0., -1.,  0.],
       [ 0.,  0.,  0., -1.]])

If you want to simultaneously swap columns and assign to a new variable, the most clear and concise way I could figure out how to do it was this:如果你想同时交换列并分配给一个新变量,我能弄清楚如何做到这一点的最清晰简洁的方法是:

import numpy as np
test_arr = np.arange(12).reshape(4,3)
swapped = np.concatenate((test_arr[:, [1,0]], test_arr[:, 2:]), axis=1)

Note, if the further columns don't exist it will concatenate an on an empty array, meaning it will just swap the first two columns.请注意,如果其他列不存在,它将连接一个空数组,这意味着它只会交换前两列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM