我正在尝试获取另一个 numpy 数组内的 numpy 数组的索引,例如,我有
y = array([1, 2, 3, 4, 5, 8])
x = np.array([3, 1, 8])
x 包含在 y 中,所以我想要得到的是索引 idx
x 数组在 y 数组上的顺序相同,所以这里是 idx = array([2, 0, 5])
这样我们就有 np.array_equal(y[idx] ,x)
产量True
,
我尝试使用 np.argwhere(np.in1d(y,x))
,但显然我没有得到相同的顺序,我知道我总是可以使用列表理解 idx = [ list(y).index(el) for el in x]
,但我更喜欢使用 numpy。
有什么想法吗?
最佳答案
来自Is there a NumPy function to return the first index of something in an array?
>>> t = array([1, 1, 1, 2, 2, 3, 8, 3, 8, 8])
>>> nonzero(t == 8)
(array([6, 8, 9]),)
>>> nonzero(t == 8)[0][0]
6
因此请根据您的情况进行调整:
lst=[]
for item in x:
lst.append( list(nonzero(y == item)) )
关于python - 获取另一个 numpy 数组中一个 numpy 数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56682344/