I want a easy to read access to some parts of a multidimensional numpy array. For any array accessing the first dimension is easy (b[index]
). Accessing the sixth dimension on the other hand is "hard" (especially to read).
b[:,:,:,:,:,index] #the next person to read the code will have to count the :
Is there a better way to do this? Especially is there a way, where the axis is not known while writing the program?
Edit: The indexed dimension is not necessarily the last dimension
An intermediate way (in readability and time) between the answers of MSeifert and kazemakase is using
np.rollaxis
:Testing the solutions:
If you want a view and want it fast you can just create the index manually:
Which is much faster than
np.take
and only marginally slower than indexing with:
s:But maybe not as readable, so if you need that often you probably should put it in a function with a meaningful name:
You can use
np.take
. For example:In the spirit of @Jürg Merlin Spaak's
rollaxis
but much faster and not deprecated:You can say: