如何使用排除对Numpy数组进行子集化

J_y*_*ang 6 python numpy

在 Numpy 中,您可以通过提供列表或整数来对某些列进行子集化。例如:

a = np.ones((10, 5))

a[:,2] or a[:,[1,3,4]]
Run Code Online (Sandbox Code Playgroud)

但是怎么排除呢?它返回除 2 或 [1,3,4] 之外的所有其他列。

原因是我想让所有其他列为零,除了一个或选定列的列表,例如:

a[:, exclude(1)] *= 0
Run Code Online (Sandbox Code Playgroud)

我可以生成一个具有相同形状的新零数组,然后将特定列分配给新变量。但我想知道是否有更有效的方法

谢谢

kab*_*nus 4

一种方法是自己生成索引列表:

>>> a[:,list(i for i in range(a.shape[1]) if i not in set((2,1,3,4)))]
array([[ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.]])
Run Code Online (Sandbox Code Playgroud)

或排除单个列(在编辑后):

>>> a[:,list(i for i in range(a.shape[1]) if i != 1)]*= 0
Run Code Online (Sandbox Code Playgroud)

或者如果你经常使用它,并且想要使用一个函数(不会被调用except,因为这是一个Python关键字:

def exclude(size,*args):
    return [i for i in range(size) if i not in set(args)] #Supports multiple exclusion
Run Code Online (Sandbox Code Playgroud)

所以现在

a[:,exclude(a.shape[1],1)]
Run Code Online (Sandbox Code Playgroud)

作品。

@jdehesa 提到 Numpy 1.13 中你可以使用

a[:, np.isin(np.arange(a.shape[1]), [2, 1, 3, 4], invert=True)]
Run Code Online (Sandbox Code Playgroud)

以及 Numpy 本身内部的某些东西。