[Numpy-discussion] yet another indexing question

Fabrice Silva silva at lma.cnrs-mrs.fr
Fri Oct 14 09:51:38 EDT 2011


Le vendredi 14 octobre 2011 à 08:04 -0400, Neal Becker a écrit :
> suppose I have:
> 
> In [10]: u
> Out[10]: 
> array([[0, 1, 2, 3, 4],
>        [5, 6, 7, 8, 9]])
> 
> And I have a vector v:
>  v = np.array ((0,1,0,1,0))
> 
> I want to form an output vector which selects items from u where v is the index 
> of the row of u to be selected.
> 
> In the above example, I want:
> 
> w = [0,6,2,8,4]
> 
> I can't seem to find a syntax that does this.
> 
> Now, more importantly, I need the result to be a reference to the original array 
> (not a copy), because I'm going to use it on the LHS of an assignment.  Is this 
> possible?

What about np.where?
http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

w = np.where(v, u[1], u[0])

if you may want to have more than two options (more than two lines for
u), then np.choose may be more appropriate
http://docs.scipy.org/doc/numpy/reference/generated/numpy.choose.html 
-- 
Fabrice Silva




More information about the NumPy-Discussion mailing list