[Numpy-discussion] use index array of len n to select columns of n x m array

John Salvatier jsalvati at u.washington.edu
Thu Aug 5 13:47:58 EDT 2010


You may also use the choose function:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.choose.html

choose(i, (a[:,0], a[:,1])

On Thu, Aug 5, 2010 at 10:31 AM, Keith Goodman <kwgoodman at gmail.com> wrote:

> On Thu, Aug 5, 2010 at 10:26 AM,  <josef.pktd at gmail.com> wrote:
> > On Thu, Aug 5, 2010 at 1:12 PM, Martin Spacek <numpy at mspacek.mm.st>
> wrote:
> >> I want to take an n x m array "a" and index into it using an integer
> index array
> >> "i" of length n that will pull out the value at the designated column
> from each
> >> corresponding row of "a".
> >>
> >>>>> a = np.arange(10)
> >>>>> a.shape = 5, 2
> >>>>> a
> >> array([[0, 1],
> >>        [2, 3],
> >>        [4, 5],
> >>        [6, 7],
> >>        [8, 9]])
> >>>>> i = np.array([0, 1, 1, 0, 1])
> >>
> >> I want:
> >>
> >>>>> b = a.foo(i)
> >>>>> b
> >> array([0, 3, 5, 6, 9])
> >>
> >> What's foo? I can't get take() to do what I want. I went and wrote my
> own little
> >> Cython function to do this, but that seems silly (and is also array
> dtype
> >> dependent). I've tried reading through the numpy book, and I'm sure this
> is
> >> somewhere on the list, but I can't find it. I think it has something to
> do with
> >> fancy indexing. I should know how to do this by know...
> >
> > like this ?
>
> Yes, I like it. Textbook case of fancy indexing.
>
> >
> >>>> a= np.array([[0, 1],
> >       [2, 3],
> >       [4, 5],
> >       [6, 7],
> >       [8, 9]])
> >>>> i = np.array([0, 1, 1, 0, 1])
> >>>> a[range(a.shape[0]), i]
> > array([0, 3, 5, 6, 9])
> >>>> a[np.arange(a.shape[0]), i]
> > array([0, 3, 5, 6, 9])
> >
> > Josef
> >
> >>
> >> Cheers,
> >>
> >> Martin
> >>
> >> _______________________________________________
> >> NumPy-Discussion mailing list
> >> NumPy-Discussion at scipy.org
> >> http://mail.scipy.org/mailman/listinfo/numpy-discussion
> >>
> > _______________________________________________
> > NumPy-Discussion mailing list
> > NumPy-Discussion at scipy.org
> > http://mail.scipy.org/mailman/listinfo/numpy-discussion
> >
> _______________________________________________
> 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/20100805/c93414f5/attachment.html>


More information about the NumPy-Discussion mailing list