[Numpy-discussion] very simple iteration question.
Anne Archibald
peridot.faceted@gmail....
Wed Apr 30 12:24:43 CDT 2008
2008/4/30 Christopher Barker <Chris.Barker@noaa.gov>:
> a g wrote:
> > OK: how do i iterate over an axis other than 0?
>
> This ties in nicely with some of the discussion about interating over
> matrices. It ahs been suggested that it would be nice to have iterators
> for matrices, so you could do:
>
> for row in M.rows:
> ...
>
> and
>
> for column in M.cols:
> ...
>
>
> If so, then wouldn't it make sense to have built in iterators for
> nd-arrays as well? something like:
>
> for subarray in A.iter(axis=i):
> ...
>
> where axis would default to 0.
>
> This is certainly cleaner than:
>
> for j in range(A.shape[i]):
> subarray = A[:,:,j,:]
>
> Wait! I have no idea how to spell that generically -- i.e. the ith
> index, where i is a variable. There must be a way to build a slice
> object dynamically, but I don't know it.
Slices can be built without too much trouble using slice(), but it's
much easier to just write
for subarray in np.rollaxis(A,i):
...
rollaxis() just pulls the specified axis to the front. (It doesn't do
what I thought it would, which is a cyclic permutation of the axes).
Anne
More information about the Numpy-discussion
mailing list