[Numpy-discussion] yet another indexing question

Warren Weckesser warren.weckesser at enthought.com
Fri Oct 14 08:59:55 EDT 2011


On Fri, Oct 14, 2011 at 7:04 AM, Neal Becker <ndbecker2 at gmail.com> wrote:

> 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?
>


In [27]: a
Out[27]:
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])

In [28]: v = array([0,1,0,1,0])

In [29]: a[v,range(5)]
Out[29]: array([0, 6, 2, 8, 4])

In [30]: a[v,range(5)] = 99

In [31]: a
Out[31]:
array([[99,  1, 99,  3, 99],
       [ 5, 99,  7, 99,  9]])


In line [29], the result is a copy, *not* a reference.  In [30], however,
the assignment does write 99 into a.

Warren



>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20111014/0a3a1e4e/attachment.html>


More information about the NumPy-Discussion mailing list