[SciPy-User] What is the best way to take elements from an array along an axis?
Alexander Kalinin
alec.kalinin@gmail....
Mon Mar 12 09:10:06 CDT 2012
Thank you, Josef!
Yes, I think
c = b[:, :1]
or
c = b[:, k:k+1]
is the most clean way to do what i want.
Sincerely,
Alexander
On Mon, Mar 12, 2012 at 6:04 PM, <josef.pktd@gmail.com> wrote:
> On Mon, Mar 12, 2012 at 9:56 AM, Alexander Kalinin
> <alec.kalinin@gmail.com> wrote:
> > Hello,
> >
> > When we use "fancy" indexing to take elements from an array along an
> axis,
> > the error could appear. Look at the code
> >
> > import numpy as np
> >
> > a = np.random.rand(10, 3)
> >
> > b = np.random.rand(10, 3)
> >
> > c = b[:, 0]
> >
> > result = a * c
> >
> >
> > We got an error: "ValueError: shape mismatch: objects cannot be
> broadcast to
> > a single shape". We have the shape problem:
> >
> >
> >>>> a.shape
> > (10, 3)
> >>>> c.shape
> > (10,)
> >>>
> >
> > I know two ways to overcome this problem:
> > 1 way:
> > c = b[:, 0].reshape(-1, 1)
> >
> >
> > 2 way:
> >
> > c = b[:, 0, np.newaxis]
> >
> >
> > But what is the best practice for this case? How I should take elements
> from
> > an array?
>
> when I know I will need it right away with the extra axis, I usually use
> slices
>
> c = b[:, :1]
> or
> c = b[:, k:k+1]
>
> numpy also has a function to add a newaxis that I often use, but it
> has such an awful name that I don't find it anymore. :)
>
> Josef
>
>
>
> >
> >
> > Sincerely,
> >
> > Alexander
> >
> >
> > _______________________________________________
> > SciPy-User mailing list
> > SciPy-User@scipy.org
> > http://mail.scipy.org/mailman/listinfo/scipy-user
> >
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20120312/449decfe/attachment.html
More information about the SciPy-User
mailing list