加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Numpy Indexing:返回休息

发布时间:2020-12-16 23:17:37 所属栏目:Python 来源:网络整理
导读:一个简单的numpy索引的例子: In: a = numpy.arange(10)In: sel_id = numpy.arange(5)In: a[sel_id]Out: array([0,1,2,3,4]) 如何返回没有被sel_id索引的数组的其余部分?我能想到的是: In: numpy.array([x for x in a if x not in a[id]])out: array([5,6,
一个简单的numpy索引的例子:
In: a = numpy.arange(10)
In: sel_id = numpy.arange(5)
In: a[sel_id]
Out: array([0,1,2,3,4])

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

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

有什么更容易的方法吗?

解决方法

对于这个简单的1D案例,我实际上使用了一个布尔蒙版:
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))])

现在你可以得到你的价值观:

included = a[mask]  # array([0,3])
excluded = a[~mask] # array([4,5,9])

请注意,[mask]不一定产生与[include_index]相同的东西,因为include_index的顺序对于该场景中的输出很重要(它应该大致相当于[sorted(include_index)]).但是,由于您排除的项目的顺序没有明确定义,所以应该可以正常工作.

编辑

创建掩码的更好方法是:

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

(感谢seberg).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读