您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – Numpy Indexing:返回休息

5b51 2022/1/14 8:22:40 python 字数 1557 阅读 536 来源 www.jb51.cc/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: arra

概述

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

有什么更容易的方法吗?

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

总结

以上是编程之家为你收集整理的python – Numpy Indexing:返回休息全部内容,希望文章能够帮你解决python – Numpy Indexing:返回休息所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶