[SciPy-User] What is the best way to take elements from an array along an axis?

josef.pktd@gmai... josef.pktd@gmai...
Mon Mar 12 09:04:28 CDT 2012


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
>


More information about the SciPy-User mailing list