【发布时间】:2015-08-21 11:14:39
【问题描述】:
如何在 numpy 数组中搜索一小组值(未排序,不应更改)? 它应该返回这些值的索引。
例如:
a = np.array(['d', 'v', 'h', 'r', 'm', 'a']) # in general it will be large
query = np.array(['a', 'v', 'd'])
# Required:
idnx = someNumpyFunction(a, query)
print(indx) # should be [5, 1, 0]
我是 numpy 的初学者,我找不到同时为多个值执行此任务的正确方法(我知道 np.where(a=='d') 可以为单个值执行此操作值搜索)。
【问题讨论】:
-
如果
query很小,并且没有严格的优化需求,我建议使用简单的for i in query: np.where(a==i)。你当然要处理边缘情况:没有匹配,不止一个匹配。 -
如果在
a中找不到query元素,你想要什么?重复呢? -
在我的情况下,查询元素是唯一的并且始终存在。但即使有一个解决方案可能返回 -1 或 outOfIndex 未找到它也没关系,但不会引发异常
标签: arrays python-3.x search numpy