# [SciPy-User] numpy array assignment

4 messages
Open this post in threaded view
|

## [SciPy-User] numpy array assignment

 Hi, I have used many times syntax like import numpy as np def result_of_long_calculation_returning_the_right_shape():   return np.random.random( (2,3) ) N=10 out = np.empty( (N,2,3) ) for i in range(N):   out[i] = result_of_long_calculation_returning_the_right_shape() if I have to loop trough the axis 1 I would do something like N=10 out = np.empty( (2,N,3) ) for i in range(N):   out[:,i,:] = result_of_long_calculation_returning_the_right_shape() The problem is that - in the function I am writing - the number of dimensions and the axis to loop trough are not known in advance. Is there a smart what to do it ? I would expect that a function like np.assign(array,element=0,axis=0) that   but I can't find such function. 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) Thanks a lot in advance, marco _______________________________________________ SciPy-User mailing list [hidden email] http://mail.scipy.org/mailman/listinfo/scipy-user
Open this post in threaded view
|

## Re: numpy array assignment

 On Thu, Apr 17, 2014 at 7:59 AM, marco cammarata 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    aCheers,Antonio  _______________________________________________ SciPy-User mailing list [hidden email] http://mail.scipy.org/mailman/listinfo/scipy-user