Numpy:对于一个数组中的每个元素,在另一个数组中找到索引

2024-05-14 00:47:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个一维阵列,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中,就可以得到加分


Tags: 方法记忆in元素内容forlennp
3条回答

我想建议一个解决方案:

indices = np.where(np.in1d(x, y))[0]

结果是一个x数组的索引数组,该数组对应于在x中找到的y元素

如果需要的话,你可以在没有核的地方使用它。

这个怎么样?

它确实假设y的每个元素都在x中(即使对于不在x中的元素也会返回结果!)但速度要快得多。

import numpy as np

# Generate some example data...
x = np.arange(1000)
np.random.shuffle(x)
y = np.arange(100)

# Actually preform the operation...
xsorted = np.argsort(x)
ypos = np.searchsorted(x[xsorted], y)
indices = xsorted[ypos]

正如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]

相关问题 更多 >