2

I have an array of unspecified dimension (it may be 1D, 2D, 3D, 4D, ...). I want to apply to reorder on the last dimension using an array of the index of the same size as the last dimension. I know how to do it with a dummy if ... if statement:

import numpy as np

a = np.ones((10, 10, 20, 40,30,10))
index=np.arange(a.shape[-1])

if len(a.shape)==1:
    a=a[index]
elif len(a.shape)==2:
    a=a[:,index]
elif len(a.shape)==3:
    a=a[:,:,index]
elif len(a.shape)==4:
    a=a[:,:,:,index]
elif  len(a.shape)==5:
    a=a[:,:,:,:,index]
else:
    print('Dimensions too high!!!')

I am of course not satisfied with this because it cannot be generalized to any dimension. I would be very grateful if someone could indicate to me the correct way to do it!

Thanks!

BayesianMonk
  • 540
  • 7
  • 23

1 Answers1

4

Simply use the ellipsis operator for a generic n-dim indexing -

a[...,index]

More info on ellipsis when indexing into arrays.

Extensive Q&A on ellipsis.

Divakar
  • 218,885
  • 19
  • 262
  • 358
  • Great! I did not know this operator, it will be very useful to me! Thanks! – BayesianMonk Aug 02 '18 at 08:44
  • Is there a way to generalize this to a case where we want to access an intermediary axis (not the first or the last)? I couldn't find any mentions on the links above. – Lucas Baldo May 20 '21 at 00:07