I have a numpy array such as arr = np.arange(16).reshape(2,2,2,2)
I want to dynamically access arr[:, dim2, dim3], when I have (dim2, dim3) as a tuple. What is the best way to do this?
I have a numpy array such as arr = np.arange(16).reshape(2,2,2,2)
I want to dynamically access arr[:, dim2, dim3], when I have (dim2, dim3) as a tuple. What is the best way to do this?
Try something like this if the number of dimensions might not be the same for your array:
some_tuple = (dim2, dim3) # Could be (dim2, dim3, ..., dimN)
arr[(slice(None),) + some_tuple]
In this particular case, (slice(None),) + some_tuple is the same as (slice(None), dim2, dim3). slice(None) is more or less equivalent to ":", but it can be used in more places than ":". Notice that I put slice(None) in a single-element tuple (i.e. (slice(None),)) so that I can add it to some_tuple. Notice as well that there's a comma after slice(None), i.e., I don't just write (slice(None)) without a comma. It won't work without the extra comma.
arr[(slice(None), *some_tuple)] could also be an option, this way you avoid creating a tuplesome_tuple = (dim2, dim3)
arr[:, some_tuple[0], some_tuple[1]]