Numpy在另一个数组中查找元素索引

Ima*_*ngo 6 python arrays indexing numpy

我有一个具有唯一正整数的数组/集,即

>>> unique = np.unique(np.random.choice(100, 4, replace=False))
Run Code Online (Sandbox Code Playgroud)

并且包含从前一个数组中采样的多个元素的数组,例如

>>> A = np.random.choice(unique, 100)
Run Code Online (Sandbox Code Playgroud)

我想将数组的值映射A到这些值出现的位置unique.

到目前为止,我找到的最佳解决方案是通过映射数组:

>>> table = np.zeros(unique.max()+1, unique.dtype)
>>> table[unique] = np.arange(unique.size)
Run Code Online (Sandbox Code Playgroud)

上面为每个元素分配了数组上的索引,因此可以在以后用于映射A高级索引:

>>> table[A]
array([2, 2, 3, 3, 3, 3, 1, 1, 1, 0, 2, 0, 1, 0, 2, 1, 0, 0, 2, 3, 0, 0, 0,
       0, 3, 3, 2, 1, 0, 0, 0, 2, 1, 0, 3, 0, 1, 3, 0, 1, 2, 3, 3, 3, 3, 1,
       3, 0, 1, 2, 0, 0, 2, 3, 1, 0, 3, 2, 3, 3, 3, 1, 1, 2, 0, 0, 2, 0, 2,
       3, 1, 1, 3, 3, 2, 1, 2, 0, 2, 1, 0, 1, 2, 0, 2, 0, 1, 3, 0, 2, 0, 1,
       3, 2, 2, 1, 3, 0, 3, 3], dtype=int32)
Run Code Online (Sandbox Code Playgroud)

哪个已经给了我正确的解决方案.但是,如果其中的唯一数字unique非常稀疏且大,则此方法意味着创建一个非常大的table数组,只是为了存储一些数字以便以后映射.

有没有更好的解决方案?

注:这两个Aunique的样本数组,不是真正的数组.所以问题不在于如何生成位置索引,它只是如何有效地将元素映射A到索引中unique,我想在numpy中加速的伪代码如下,

B = np.zeros_like(A)
for i in range(A.size):
    B[i] = unique.index(A[i])
Run Code Online (Sandbox Code Playgroud)

(假设unique是上述伪代码中的列表).

Bi *_*ico 4

当您的问题中描述的表格方法unique非常密集时,它是最好的选择,但unique.searchsorted(A)应该产生相同的结果并且不需要unique密集。searchsorted对于整数来说很棒,如果有人试图用有精度限制的浮点数做这种事情,请考虑这样的事情