首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >用于同一条目的多个实例的numpy.searchsorted

用于同一条目的多个实例的numpy.searchsorted
EN

Stack Overflow用户
提问于 2018-10-16 02:31:23
回答 1查看 92关注 0票数 0

我有以下变量:

将numpy导入为np

代码语言:javascript
复制
gens = np.array([2, 1, 2, 1, 0, 1, 2, 1, 2])
p = [0,1]

我想返回与p的每个元素相匹配的gens条目。

所以理想情况下,我希望它返回:

代码语言:javascript
复制
result = [[4],[2,3,5,7],[0,2,6,8]] 
#[[where matched 0], [where matched 1], [the rest]]

--

到目前为止,我的尝试只对一个变量有效:

代码语言:javascript
复制
indx = gens.argsort()
res = np.searchsorted(gens[indx], [0])
gens[res] #gives 4, which is the position of 0

但我试着用

代码语言:javascript
复制
indx = gens.argsort()
res = np.searchsorted(gens[indx], [1])
gens[res] #gives 1, which is the position of the first 1.

所以:

如何搜索具有多个occurrences

  • how的条目
  • 如何搜索每个条目都具有多个occurrences?

的多个条目

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-16 03:06:11

您可以使用np.where

代码语言:javascript
复制
>>> np.where(gens == p[0])[0]
array([4])

>>> np.where(gens == p[1])[0]
array([1, 3, 5, 7])

>>> np.where((gens != p[0]) & (gens != p[1]))[0]
array([0, 2, 6, 8])

或者np.in1dnp.nonzero

代码语言:javascript
复制
>>> np.nonzero(np.in1d(gens, p[0]))[0]

>>> np.nonzero(np.in1d(gens, p[1]))[0]

>>> np.nonzero(~np.in1d(gens, p))[0]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52822772

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档