繁体   English   中英

从numpy数组中提取不在索引列表中的元素

[英]Extract elements from numpy array, that are not in list of indexes

我想做类似于NumPy数组所要求的内容,更改不在索引列表中的值 ,但不完全相同。

考虑一个numpy数组:

> a = np.array([0.2, 5.6, 88, 12, 1.3, 6, 8.9])

我知道我可以通过索引列表访问其元素,例如:

> indxs = [1, 2, 5] 
> a[indxs]
array([  5.6,  88. ,   6. ])

但我还需要访问那些不在 indxs列表中的indxs 天真地,这是:

> a[not in indxs]
> array([0.2, 12, 1.3, 8.9])

这样做的正确方法是什么?

一种方法是使用布尔掩码并将索引反转为false:

mask = np.ones(a.size, dtype=bool)
mask[indxs] = False
a[mask]

一种方法是使用np.in1dindxs创建一个掩码,然后将其反转并使用它为所需输出索引输入数组 -

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM