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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With