倒置的花式索引

6

如果有一个数组和一个用于该数组的掩码,使用高级索引,很容易只选择与掩码对应的数组数据。

import numpy as np

a = np.arange(20).reshape(4, 5)
mask = [0, 2]
data = a[:, mask]

但是,有没有一种快速的方法来选择数组中所有不属于掩码的数据(即掩码是我们想要拒绝的数据)?我试图通过一个中间的布尔数组找到一个通用的解决方案,但我相信肯定有更简单的方法。

mask2 = np.ones(a.shape)==1
mask2[:, mask]=False
data = a[mask2].reshape(a.shape[0], a.shape[1]-size(mask))

感谢您的选择。
1个回答

9
请看numpy.invertnumpy.bitwise_notnumpy.logical_not或更简洁的~mask。在这种情况下,它们都执行相同的操作。

以下是一个快速的示例:

import numpy as np

x = np.arange(10)
mask = x > 5

print x[mask]
print x[~mask]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接