numpy:对于一个数组中的每个元素,在另一个数组中找到索引
我有两个一维数组x和y,一个比另一个小。我试图找到x中y的每个元素的索引。
我发现有两种简单的方法可以做到这一点,第一种很慢,第二种需要占用大量内存。
缓慢的方式
indices= []
for iy in y:
indices += np.where(x==iy)[0][0]
记忆猪
xe = np.outer([1,]*len(x), y)
ye = np.outer(x, [1,]*len(y))
junk, indices = np.where(np.equal(xe, ye))
是否有更快的方法或更少的内存密集型方法?理想情况下,搜索将利用以下事实:我们不是在列表中搜索一件事,而是在搜索许多东西,因此稍微适合并行化。如果您不假设y的每个元素实际上都在x中,则可获得加分。
-
正如Joe
Kington所说,searchsorted()可以非常快速地搜索元素。要处理不在x中的元素,可以用原始y检查搜索结果,并创建一个掩码数组:import numpy as np x = np.array([3,5,7,1,9,8,6,6]) y = np.array([2,1,5,10,100,6]) index = np.argsort(x) sorted_x = x[index] sorted_index = np.searchsorted(sorted_x, y) yindex = np.take(index, sorted_index, mode="clip") mask = x[yindex] != y result = np.ma.array(yindex, mask=mask) print result
结果是:
[-- 3 1 -- -- 6]