I am trying to define a function that returns elements of a multi-dimensional variable according to a nested list of indices. I am working with variables depending on multiple dimensions like, e.g.: time, altitude, latitude, longitude.
Make it 3D for now (e.g., time, altitude and latitude):
x = np.arange(125).reshape(5,5,5)
If I now want the first 4 time steps, the first 3 altitude levels and the first 2 latitudes I can do several things:
x[[0,1,2,3],:,:][:,[0,1,2],:][:,:,[0,1]]
or
x[ [[[0]],[[1]],[[2]],[[3]]],[[0],[1],[2]],[0,1]]
or
x[np.ix_([0,1,2,3],[0,1,2],[0,1])]
But what I would like to have is a function giving me back the elements like
def get_elements( x, l )
where l
is a list of indices
l = [[0,1,2,3],[0,1,2],[0,1]]
How could this function look like? The last alternative comes pretty close but x[np.ix_(l)]
gives me an IndexError
.
Moreover, it would be great to have the opportunity to leave dimensions untouched. E.g., using all time steps in this pseudo-code:
l = [[:],[0,1,2],[0,1]]
Thanks a lot!