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

Alexander Kalinin alec.kalinin@gmail....
Mon Mar 12 08:56:47 CDT 2012


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

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?


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20120312/96a94bd9/attachment.html 

More information about the SciPy-User mailing list