您可以使用
in1d和
nonzero(或
where为此):
>>> np.in1d(b, a).nonzero()[0]array([0, 1, 4])
这对于您的示例数组很好用,但是通常返回的索引数组不遵循中的值顺序
a。这可能是个问题,具体取决于您下一步要做什么。
在这种情况下,更好的答案是一个@Jaime给出了这里,使用
searchsorted:
>>> sorter = np.argsort(b)>>> sorter[np.searchsorted(b, a, sorter=sorter)]array([0, 1, 4])
返回值在中出现的索引
a。例如:
a = np.array([1, 2, 4])b = np.array([4, 2, 3, 1])>>> sorter = np.argsort(b)>>> sorter[np.searchsorted(b, a, sorter=sorter)]array([3, 1, 0]) # the other method would return [0, 1, 3]



