[英]Find all indices of numpy vector whose value is in a given set
I am getting more and more used to numpy
's fancy indexing possibilities, but this time I hit an obstacle I cannot solve without resorting to ugly for loops. 我越来越习惯于
numpy
的花式索引的可能性,但是这次我遇到了一个障碍,如果不诉诸于丑陋的for循环,我将无法解决。
My input is a pair of vectors, one large vector v
and a smaller vector of indices e
. 我的输入是一对向量,一个大向量
v
和一个较小的索引e
向量。 What I want is to find all the indices i
for which v[i]
is equal to one of the values v[e[0]], v[e[1]],...v[e[n]]
. 我想要找到的所有索引
i
的v[i]
等于值v[e[0]], v[e[1]],...v[e[n]]
。 At the moment, the code that does this for me (and it works) is 目前,为我执行此操作的代码(并且有效)是
import numpy as np
v = np.array([0,0,0,0,1,1,1,2,2,2,2,2,2])
e=np.array([0,4])
#what I want to get is the vector [0,1,2,3,4,5,6].
values = v[e]
r = []
for i in range(n):
if v[i] in values:
r.append(i)
In the case when e
is only one number, I am able to do this: 在
e
仅是一个数字的情况下,我可以执行以下操作:
rr = np.arange(n)
r = v[rr] == v[e]
which is both nicer and quicker than a for loop. 这比for循环更好更快。 Is there a way of doing this when
e
is not a single number? 当
e
不是一个整数时,有没有办法做到这一点?
You could use where
and in1d
: 您可以使用
where
和in1d
:
>>> v = np.array([0,0,0,0,1,1,1,2,2,2,2,2,2])
>>> e = [0,4]
>>> np.in1d(v, v[e])
array([ True, True, True, True, True, True, True, False, False,
False, False, False, False], dtype=bool)
>>> np.where(np.in1d(v, v[e]))
(array([0, 1, 2, 3, 4, 5, 6]),)
>>> np.where(np.in1d(v, v[e]))[0]
array([0, 1, 2, 3, 4, 5, 6])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.