[Numpy-discussion] Assignment when there is nothing to assign

Keith Goodman kwgoodman at gmail.com
Thu Dec 21 14:17:20 EST 2006


On 12/21/06, Keith Goodman <kwgoodman at gmail.com> wrote:
> I have the following two lines in a for loop:
>
> if len(idx):
>     x[idx,i] = x[idx,i-1]
>
> where idx is the output of a where statement.
>
> I need the 'if len(idx)' line to prevent an error when idx is empty.
>
> Would it make sense to allow
>
> x[idx,i] = x[idx,i-1]
>
> when idx is empty instead of raising an error?
>
> The error I get is
>
> ValueError: array is not broadcastable to correct shape

Why doesn't this work?

>> y

matrix([[ 0.93473209,  0.34122426],
        [ 0.68353656,  0.77589206],
        [ 0.50677768,  0.25089722]])
>> idx = M.array([1, 2])
>> y[idx,0]                              <------this works

matrix([[ 0.68353656],
        [ 0.50677768]])
>> y[idx,0] = y[idx,1]             <------but this doesn't
---------------------------------------------------------------------------
exceptions.ValueError                                Traceback (most
recent call last)

ValueError: array is not broadcastable to correct shape


But this works:

>> idx = M.asarray(M.asmatrix(idx).T)
>> y[idx,0] = y[idx,1]



More information about the NumPy-Discussion mailing list