numpy 数组之间的交叉引用

Cross-reference between numpy arrays

我有一个 id 数组,例如:

a = [1, 3, 4, 7, 9]

然后是另一个二维数组:

b = [[1, 4, 7, 9], [3, 7, 9, 1]]

我想要第三个数组,其形状与 b 相同,其中每个项目都是 a 中对应项目的索引,即:

c = [[0, 2, 3, 4], [1, 3, 4, 0]]

使用 numpy 的矢量化方法是什么?

广播来拯救!

>>> ((np.arange(1, len(a) + 1)[:, None, None]) * (a[:, None, None] == b)).sum(axis=0) - 1
array([[0, 2, 3, 4],
       [1, 3, 4, 0]])

这可能没有意义,但是......你可以使用 np.interp 来做到这一点......

a = [1, 3, 4, 7, 9]
sorting = np.argsort(a)
positions = np.arange(0,len(a))
xp = np.array(a)[sorting]
fp = positions[sorting]
b = [[1, 4, 7, 9], [3, 7, 9, 1]]
c = np.rint(np.interp(b,xp,fp)) # rint is better than astype(int) because floats are tricky.
# but astype(int) should work faster for small len(a) but not recommended.

只要 len(a) 小于 float (16,777,217) 最大可表示的 int ....并且此算法的速度为 O(n*log(n)),(或者确切地说是 len(b)*log(len(a))

实际上,这个解决方案是 one-liner。唯一的问题是您需要在执行 one-liner 之前重塑数组,然后再次重塑它:

import numpy as np

a = np.array([1, 3, 4, 7, 9])
b = np.array([[1, 4, 7, 9], [3, 7, 9, 1]])
original_shape = b.shape

c = np.where(b.reshape(b.size, 1) == a)[1]

c = c.reshape(original_shape)

结果为:

[[0 2 3 4]
 [1 3 4 0]]