本文介绍了从numpy数组中提取不在索引列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的事情与这里,但不完全相同.

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数组:

> 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. ])

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

But I also need to access those elements which are not in the indxs list. Naively, this is:

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

执行此操作的正确方法是什么?

What is the proper way to do this?

推荐答案

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比您真正需要的更通用,根据输入使用不同的策略.我认为在这种情况下,它使用布尔掩码方法(时序应该相似).

delete is more general than you really need, using different strategies depending on the inputs. 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])

这篇关于从numpy数组中提取不在索引列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:33