获得几个元素的索引在numpy的阵列一次 [英] Getting the indices of several elements in a NumPy array at once
问题描述
有没有什么办法让一个numpy的数组的几个元素的索引一次?
例如
导入numpy的是NP
一个= np.array([1,2,4])
B = np.array([1,2,3,10,4])
我想找到 A
在 B
,即每个元素的索引: [0,1,4]
。
我发现我使用的是有点冗长的解决方案:
导入numpy的是NP一个= np.array([1,2,4])
B = np.array([1,2,3,10,4])C = np.zeros_like(一)
对于我,AA在np.ndenumerate(一):
C [i] = np.where(B == AA)[0]打印('C:{0}。格式(C))
输出:
C:[0 1 4]
您可以使用 in1d
和<一个href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html\"><$c$c>nonzero$c$c> (或其中,
对于这个问题):
&GT;&GT;&GT; np.in1d(B,A).nonzero()[0]
阵列([0,1,4])
这正常工作对你的榜样阵列,但一般返回指数的阵列不兑现值的的顺序
。这可能取决于你下一步想做什么是个问题。
在这种情况下,一个更好的答案是一个@Jaime这里给,使用 searchsorted
:
&GT;&GT;&GT;分拣机= np.argsort(二)
&GT;&GT;&GT;分拣机[np.searchsorted(B,A,分拣机分拣机=)
阵列([0,1,4])
这是他们出现在 A
返回指数值。例如:
A = np.array([1,2,4])
B = np.array([4,2,3,1])&GT;&GT;&GT;分拣机= np.argsort(二)
&GT;&GT;&GT;分拣机[np.searchsorted(B,A,分拣机分拣机=)
阵列([3,1,0])#其他方法将返回[0,1,3]
Is there any way to get the indices of several elements in a NumPy array at once?
E.g.
import numpy as np
a = np.array([1, 2, 4])
b = np.array([1, 2, 3, 10, 4])
I would like to find the index of each element of a
in b
, namely: [0,1,4]
.
I find the solution I am using a bit verbose:
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))
Output:
c: [0 1 4]
You could use in1d
and nonzero
(or where
for that matter):
>>> np.in1d(b, a).nonzero()[0]
array([0, 1, 4])
This works fine for your example arrays, but in general the array of returned indices does not honour the order of the values in a
. This may be a problem depending on what you want to do next.
In that case, a much better answer is the one @Jaime gives here, using searchsorted
:
>>> sorter = np.argsort(b)
>>> sorter[np.searchsorted(b, a, sorter=sorter)]
array([0, 1, 4])
This returns the indices for values as they appear in a
. For instance:
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]
这篇关于获得几个元素的索引在numpy的阵列一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!