如何获取连接两个一维数组的索引列表?

How to get the list of indices connecting two 1-d arrays?

假设 A 和 B 是两个不同大小的一维数组,使得 pythonically B = A[C] 其中 C 是满足某些特定但已知条件的特定索引列表.如果 A 和 B 都已知,如何得到 C?我试过 C = np.where(np.close(A, B)) 但我收到以下错误消息:

File "/home/username/../my_script.py", line 897, in get_histogram
    i0, i1 = np.where(np.isclose(hist_xs, vals1)), np.where(np.isclose(hist_ys, vals2))
  File "<__array_function__ internals>", line 6, in isclose
  File "/usr/local/anaconda3/lib/python3.7/site-packages/numpy/core/numeric.py", line 2260, in isclose
    return within_tol(x, y, atol, rtol)
  File "/usr/local/anaconda3/lib/python3.7/site-packages/numpy/core/numeric.py", line 2246, in within_tol
    return less_equal(abs(x-y), atol + rtol * abs(y))
ValueError: operands could not be broadcast together with shapes (722,) (1536,)

换句话说,我试图只获取 A 的那些元素,其右索引对应于已知的 B 数组。

你在找这个吗?:

sorti = np.argsort(A)
C_inv = sorti[np.searchsorted(A,B,sorter=sorti)]

示例代码(适用于任何可排序数组,如果您的数组元素没有比较运算符,您可以自己编写。如果 (less/greater) 比较不适用,您将需要一个 for 循环找到似乎很容易包含在这里的元素):

A: [89 28 86 73 29 71 37 46 15 52]
B: [86 52 15]
C: [2 9 8]
C_inv: [2 9 8]