How to subset Numpy array with exclusion

时间:2019-04-08 12:48:11

标签: python numpy

In Numpy you can subset certain columns by giving a list or integer. For example:

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

a[:,2] or a[:,[1,3,4]]

But how to do exclusion ? Where it return all other columns except 2 or [1,3,4].

The reason is that I want to make all other columns zeros except one or a list of selected columns, for example:

a[:, exclude(1)] *= 0

I can generate a new zeros array with the same shape then just assign the specific column to the new variable. But I wonder if there is any more efficient way

Thanks

2 个答案:

答案 0 :(得分:3)

One way is to generate the index list yourself:

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

or to exclude a single column (following your edit):

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

or if you use this often, and want to use a function (which will not be called except, since that is a Python keyword:

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

so now

a[:,exclude(a.shape[1],1)]

works.

@jdehesa mentions from Numpy 1.13 you can use

a[:, np.isin(np.arange(a.shape[1]), [2, 1, 3, 4], invert=True)]

as well for something within Numpy itself.

答案 1 :(得分:0)

np.delete使用布尔掩码删除/选择项。

In [27]: arr = np.arange(24).reshape(3,8)                                       

In [29]: mask = np.ones(arr.shape[1], bool)                                     
In [30]: mask[[1,3,4]] = False                                                  
In [31]: mask                                                                   
Out[31]: array([ True, False,  True, False, False,  True,  True,  True])

In [32]: arr[:,mask]                                                            
Out[32]: 
array([[ 0,  2,  5,  6,  7],
       [ 8, 10, 13, 14, 15],
       [16, 18, 21, 22, 23]])
In [33]: arr[:,mask] *= 0                                                       
In [34]: arr                                                                    
Out[34]: 
array([[ 0,  1,  0,  3,  4,  0,  0,  0],
       [ 0,  9,  0, 11, 12,  0,  0,  0],
       [ 0, 17,  0, 19, 20,  0,  0,  0]])

很容易翻转诸如面具之类的东西:

In [35]: arr[:,~mask]                                                           
Out[35]: 
array([[ 1,  3,  4],
       [ 9, 11, 12],
       [17, 19, 20]])