[SciPy-user] problem ValueError: array is not broadcastable to correct shape - convert shape (x, ) to (x, 1)
David Cournapeau
david@ar.media.kyoto-u.ac...
Sun Jan 11 22:03:03 CST 2009
Tan Tran wrote:
> Hello,
>
> I'm trying to convert a command like this in matlab to python numpy
> mysel((col3 ==11 & (col4 ==16)) = y((col3 ==11 & (col4 ==16)), col0);
>
> from numpy import *
>
> y = array([ [ 0, 1,11,15, 4], \
> [10,11,12,16,14], \
> [20,21,11,17,24], \
> [30,31,12,15,34], \
> [40,41,11,16,44], \
> [50,51,12,17,54], \
> [60,61,11,15,64], \
> [70,71,11,16,74], \
> [80,81,11,17,84], \
> [90,91,12,15,94]])
>
> col3 = 2
> col4 = 3
> col0 = 0
> mysel = zeros((10, 1),int)
>
> mypick = y[:,col0][(y[:,col3] == 11) & (y[:,col4] == 16)]
> print mypick
> print mypick.shape
>
> aa = mysel[(y[:,col3] == 11) & (y[:,col4] == 16)]
> print aa
> print aa.shape
>
> mysel[(y[:,col3] == 11) & (y[:,col4] == 16)] = mypick <-- error here
> ValueError: array is not broadcastable to correct shape
>
>
> I check the shape of two sides and see they are not adequate. The
> shape of mypick is (2,) and the shape of mysel[(y[:,col3] == 11) &
> (y[:,col4] == 16)] is (2,1).
> I have a problem selecting elements in numpy. It's always return
> something with shape (x,). How can I reformat it to the shape that I
> want like (x,1)?
This should do it:
import numpy as np
a = np.random.randn(10, 2) # 10 rows, 2column array
a1 = a[:, 0] # first column, (10,) array
a1 = a[:, 0:1] # column 0 to 1, 1 not included -> (10, 1) array
David
More information about the SciPy-user
mailing list