[英]How to extract a list of elements given by their indices from a numpy array efficiently?
[英]Extract elements from numpy array, that are not in list of indexes
一种方法是使用布尔掩码并将索引反转为false:
mask = np.ones(a.size, dtype=bool)
mask[indxs] = False
a[mask]
一种方法是使用np.in1d
从indxs
创建一个掩码,然后将其反转并使用它为所需输出索引输入数组 -
a[~np.in1d(np.arange(a.size),indxs)]
In [170]: a = np.array([0.2, 5.6, 88, 12, 1.3, 6, 8.9])
In [171]: idx=[1,2,5]
In [172]: a[idx]
Out[172]: array([ 5.6, 88. , 6. ])
In [173]: np.delete(a,idx)
Out[173]: array([ 0.2, 12. , 1.3, 8.9])
delete
比您真正需要的更通用,根据输入使用不同的策略。 我认为在这种情况下它使用布尔掩码方法(时序应该类似)。
In [175]: mask=np.ones_like(a, bool)
In [176]: mask
Out[176]: array([ True, True, True, True, True, True, True], dtype=bool)
In [177]: mask[idx]=False
In [178]: mask
Out[178]: array([ True, False, False, True, True, False, True], dtype=bool)
In [179]: a[mask]
Out[179]: array([ 0.2, 12. , 1.3, 8.9])
您可以使用枚举函数,不包括索引:
[x for i, x in enumerate(a) if i not in [1, 2, 5] ]
包括他们:
[x for i, x in enumerate(a) if i in [1, 2, 5]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.