好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

在Python中一次获取NumPy数组中的几个元素的索引

有没有办法一次获取NumPy数组中的几个元素的索引?

例如.

import numpy as np
a = np.array([1, 2, 4])
b = np.array([1, 2, 3, 10, 4])

我想找到a中每个元素的索引,即:[0,1,4].

我发现我使用的解决方案有点冗长:

import numpy as np

a = np.array([1, 2, 4])
b = np.array([1, 2, 3, 10, 4])

c = np.zeros_like(a)
for i, aa in np.ndenumerate(a):
    c[i] = np.where(b==aa)[0]

print('c: {0}'.format(c))

输出:

c: [0 1 4]
您可以使用 in1d 和 nonzero (或者就此而言):

>>> np.in1d(b, a).nonzero()[0]
array([0, 1, 4])

这适用于您的示例数组,但通常返回的索引数组不符合a中值的顺序.这可能是一个问题,具体取决于您下一步要做什么.

在这种情况下,一个更好的答案是@Jaime使用searchsorted给出here:

>>> sorter = np.argsort(b)
>>> sorter[np.searchsorted(b, a, sorter=sorter)]
array([0, 1, 4])

这将返回值中的值的索引.例如:

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]

查看更多关于在Python中一次获取NumPy数组中的几个元素的索引的详细内容...

  阅读:26次