[SciPy-User] numpy array assignment

Mark Daoust daoust.mj at gmail.com
Fri Apr 18 06:39:16 EDT 2014


Using slices and tuples, as suggested by Antonio, we can redo your original
example like this:

    colon = (slice(None),)
    out[colon*axis+(i,)+colon*(nDim-axis-1,)]=result

Ellipsis, which represents "as many colons as are needed", can simplify it
farther:

    out[colon*axis+(i,...)]=result

but numpy slicing always has an implied trailing ellipsis so, I think, this
is equivalent:

    out[colon*axis+(i,)]=result

The ellipses are more useful if you have a "negative" axis, counting from
the right instead of left. For example you can hit all but the last (-1)
and second to last (-2) axis  with:

    out[...,i]=result
    out[...,i,:]=result

or all but axis (-n) with:

    out[(...,i)+colon*(n)] = result




Mark Daoust


> You can build the tuple programmatically. Another example:
> >
> >     import numpy as np
> >     a = np.arange(1000).reshape(10, 5, 20)
> >     index = (slice(None), slice(0, 1), slice(None))
> >
> >     a[index] = 3
> >     a
> >
> >
> > Cheers,
> > Antonio
> >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.scipy.org/pipermail/scipy-user/attachments/20140418/07ad2369/attachment.html>


More information about the SciPy-User mailing list