如何在Python中从数组(或矩阵)中提取所有列但排除一列?

37 投票
4 回答
72142 浏览
提问于 2025-04-18 08:30

给定一个numpy的二维数组(或者说矩阵),我想要提取出所有的列,除了第i列。

比如,从

1 2 3 4
2 4 6 8
3 6 9 12

我想要得到,比如说:

1 2 3
2 4 6
3 6 9

或者

1 2 4
2 4 8
3 6 12

我找不到一种很“python”的方法来做到这一点。我知道你可以通过简单地

a[:,n]

或者

a[:,[n,n+1,n+5]]

但是,提取出所有列,除了其中一列,应该怎么做呢?

4 个回答

0

已经给出的答案可以很容易地调整为选择除了某些列以外的所有列,不过这里有几个明确的例子:

In [1]: import numpy as np
In [2]: a = np.arange(12).reshape(3, 4)
In [3]: a
Out[3]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [4]: drop_cols = [0, 3]

# option 1: delete the columns you don't want (like @Jaime)
# (this is really the most straightforward)

In [5]: np.delete(a, drop_cols, axis=1)
Out[5]:
array([[ 1,  2],
       [ 5,  6],
       [ 9, 10]])

# option 2: pass the indices of columns to keep (like @chrisb)

In [6]: a[:, [i for i in range(a.shape[1]) if i not in drop_cols]]
Out[6]:
array([[ 1,  2],
       [ 5,  6],
       [ 9, 10]])

# option 3: use an array of T/F for each col (like @Peter Gibson)

In [7]: a[:, [i not in drop_cols for i in range(a.shape[1])]]
Out[7]:
array([[ 1,  2],
       [ 5,  6],
       [ 9, 10]])
11

看看numpy的高级切片功能

>>> import numpy as np
>>> a = np.array([[1,2,3,4], [2,4,6,8], [3,6,9,12]])
>>> a[:,np.array([True, True, False, True])]
array([[ 1,  2,  4],
       [ 2,  4,  8],
       [ 3,  6, 12]])
34

使用一个切片,排除掉最后一个元素。

In [19]: a[:,:-1]
Out[19]: 
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])

如果你想要的不是最后一个元素,我建议你先建立一个列表来选择。

In [20]: selector = [x for x in range(a.shape[1]) if x != 2]
In [21]: a[:, selector]
Out[21]: 
array([[ 1,  2,  4],
       [ 2,  4,  8],
       [ 3,  6, 12]])

http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

49

因为在一般情况下,你最终会返回一个副本,所以你可能会发现使用 np.delete 可以让你的代码更容易读懂:

>>> a = np.arange(12).reshape(3, 4)
>>> np.delete(a, 2, axis=1)
array([[ 0,  1,  3],
       [ 4,  5,  7],
       [ 8,  9, 11]])

撰写回答