[SciPy-User] numpy array assignment
marco cammarata
marcocamma at gmail.com
Fri Apr 18 03:51:32 EDT 2014
Antonino Ingargiola <tritemio <at> gmail.com> writes:
>
>
> On Thu, Apr 17, 2014 at 7:59 AM, marco cammarata <marcocamma <at>
gmail.com> wrote:
>
>
>
>
> For the moment I ended up doing something really really inelegant:
> res = result_of_long_calculation_returning_the_right_shape()
> s = "out[" + (":,")*axis + "i" + (",:")*(nDim-axis-1) + "]=res"
> exec(s)
>
>
> When you do a[:, :, :], that's just syntactic sugar for a[(slice(None),
slice(None), slice(None),)] (note that slice(None) means take all elements).
In other words, the index of a ndarray is a tuple of objects/slices.
>
> 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
>
>
>
>
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User <at> scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
Antonio,
thanks for your comment.
Indeed your solution is better than mine because avoid the exec but would
still require the construction of the tuple by checking the axis and the
number of dimension.
What I was really looking for is a more general (compact) solution.
Thanks anyway,
ciao
marco
More information about the SciPy-User
mailing list