[Numpy-discussion] Selecting columns of a matrix
Bill Baxter
wbaxter at gmail.com
Wed Jun 21 00:48:48 EDT 2006
On 6/21/06, Erin Sheldon <erin.sheldon at gmail.com> wrote:
>
> On 6/20/06, Bill Baxter <wbaxter at gmail.com> wrote:
> > I think that one's on the NumPy for Matlab users, no?
> >
> > http://www.scipy.org/NumPy_for_Matlab_Users
> >
> > >>> import numpy as num
> > >>> a = num.arange (10).reshape(2,5)
> > >>> a
> > array([[0, 1, 2, 3, 4],
> > [5, 6, 7, 8, 9]])
> > >>> v = num.rand(5)
> > >>> v
> > array([ 0.10934855, 0.55719644, 0.7044047 , 0.19250088, 0.94636972])
> > >>> num.where(v>0.5)
> > (array([1, 2, 4]),)
> > >>> a[:,num.where(v>0.5)]
> > array([[[1, 2, 4]],
> >
> > [[6, 7, 9]]])
> >
> > Seems it grows an extra set of brackets for some reason. Squeeze will
> get
> > rid of them.
> >
> > >>> a[:,num.where(v>0.5)].squeeze()
> > array([[1, 2, 4],
> > [6, 7, 9]])
> >
> > Not sure why the squeeze is needed. Maybe there's a better way.
>
> where returns a tuple of arrays. This can have unexpected results
> so you need to grab what you want explicitly:
>
> >>> (w,) = num.where(v>0.5)
> >>> a[:,w]
> array([[1, 2, 4],
> [6, 7, 9]])
>
Ah, yeh, that makes sense. Thanks for the explanation. So to turn it back
into a one-liner you just need:
>>> a[:,num.where(v>0.5)[0]]
array([[1, 2, 4],
[6, 7, 9]])
I'll put that up on the Matlab->Numpy page.
--bb
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20060621/ea04ccb5/attachment.html>
More information about the NumPy-Discussion
mailing list