numpy索引:其余返回 [英] Numpy Indexing: Return the rest

查看:158
本文介绍了numpy索引:其余返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的numpy索引示例:

A simply example of numpy indexing:

In: a = numpy.arange(10)
In: sel_id = numpy.arange(5)
In: a[sel_id]
Out: array([0,1,2,3,4])

如何返回未由sel_id索引的数组的其余部分?我能想到的是:

How do I return the rest of the array that are not indexed by sel_id? What I can think of is:

In: numpy.array([x for x in a if x not in a[id]])
out: array([5,6,7,8,9])

有没有更简单的方法?

Is there any easier way?

推荐答案

对于这种简单的一维情况,我实际上将使用布尔掩码:

For this simple 1D case, I'd actually use a boolean mask:

a = numpy.arange(10)
include_index = numpy.arange(4)
include_idx = set(include_index)  #Set is more efficient, but doesn't reorder your elements if that is desireable
mask = numpy.array([(i in include_idx) for i in xrange(len(a))])

现在您可以获取自己的值了:

Now you can get your values:

included = a[mask]  # array([0, 1, 2, 3])
excluded = a[~mask] # array([4, 5, 6, 7, 8, 9])

请注意,a[mask]不一定会产生与a[include_index]相同的结果,因为在这种情况下,include_index的顺序对于输出很重要(它应大致等同于a[sorted(include_index)]).但是,由于未明确定义排除项目的顺序,因此应该可以.

Note that a[mask] doesn't necessarily yield the same thing as a[include_index] since the order of include_index matters for the output in that scenario (it should be roughly equivalent to a[sorted(include_index)]). However, since the order of your excluded items isn't well defined, this should work Ok.

编辑

创建蒙版的更好方法是:

A better way to create the mask is:

mask = np.zeros(a.shape,dtype=bool)
mask[include_idx] = True

(感谢seberg).

这篇关于numpy索引:其余返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆