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

问题描述 投票:1回答:1

假设A和B是两个不同大小的1d数组,所以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数组。

arrays python-3.x numpy numpy-ndarray indices
1个回答
1
投票

您在寻找这个吗?:

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

示例代码(它可用于任何可排序的数组,如果您的数组元素没有比较运算符,则可以编写自己的代码。如果(较小/更大)比较不适用,则需要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]
© www.soinside.com 2019 - 2024. All rights reserved.