如何从python中的数组(或矩阵)中提取所有列但只提取一列?

时间:2014-06-04 00:16:10

标签: python arrays numpy matrix

给定一个numpy 2d数组(或矩阵),我想提取所有列,但第i个。

电子。 G。从

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

我想拥有,例如<​​/ p>

1 2 3
2 4 6
3 6 9

1 2 4
2 4 8
3 6 12

我找不到这样做的pythonic方法。我现在只需

即可提取给定的列
a[:,n]

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

但是除了一个之外提取所有这些呢?

4 个答案:

答案 0 :(得分:20)

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

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

答案 1 :(得分:20)

因为对于一般情况,您无论如何都要返回副本,您可能会发现自己使用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]])

答案 2 :(得分:7)

看看numpy的advanced slicing

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

答案 3 :(得分: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]])