I have a multidimensional numpy array, and I need to iterate across a given dimension. Problem is, I won’t know which dimension until runtime. In other words, given an array m, I could want
m[:,:,:,i] for i in xrange(n)
or I could want
m[:,:,i,:] for i in xrange(n)
etc.
I imagine that there must be a straightforward feature in numpy to write this, but I can’t figure out what it is/what it might be called. Any thoughts?
There are many ways to do this. You could build the right index with a list of slices, or perhaps alter
m‘s strides. However, the simplest way may be to usenp.swapaxes:Let
axisbe the axis you wish to loop over.m_swappedis the same asmexcept theaxis=1axis is swapped with the last (axis=-1) axis.Now you can just loop over the last axis:
Note that
m_swappedis a view, not a copy, ofm. Alteringm_swappedwill alterm.