[英]Extract elements from numpy array, that are not in list of indexes
I want to do something similar to what was asked here NumPy array, change the values that are NOT in a list of indices , but not quite the same. 我想做类似于NumPy数组所要求的内容,更改不在索引列表中的值 ,但不完全相同。
Consider a numpy
array: 考虑一个
numpy
数组:
> a = np.array([0.2, 5.6, 88, 12, 1.3, 6, 8.9])
I know I can access its elements via a list of indexes, like: 我知道我可以通过索引列表访问其元素,例如:
> indxs = [1, 2, 5]
> a[indxs]
array([ 5.6, 88. , 6. ])
But I also need to access those elements which are not in the indxs
list. 但我还需要访问那些不在
indxs
列表中的indxs
。 Naively, this is: 天真地,这是:
> a[not in indxs]
> array([0.2, 12, 1.3, 8.9])
What is the proper way to do this? 这样做的正确方法是什么?
One way is to use a boolean mask and just invert the indices to be false: 一种方法是使用布尔掩码并将索引反转为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
is more general than you really need, using different strategies depending on the inputs. delete
比您真正需要的更通用,根据输入使用不同的策略。 I think in this case it uses the boolean mask approach (timings should be similar). 我认为在这种情况下它使用布尔掩码方法(时序应该类似)。
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])
You could use the enumerate function, excluding the indexes: 您可以使用枚举函数,不包括索引:
[x for i, x in enumerate(a) if i not in [1, 2, 5] ]
including them: 包括他们:
[x for i, x in enumerate(a) if i in [1, 2, 5]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.