Q:

Automatically switching dimension in array indexing (python)

I want to automatize the following operation in Python. Given a n-dimensional np.array, e.g.
ar = np.array([[[ 8, 10],
                [ 9, 11],
                [10, 12]],
               [[ 9, 11],
                [10, 12],
                [11, 13]]])

With names for each of the dimensions in dim_names, e.g.
dim_names = ['A','B','C']

select all the marginals of any given dimension, e.g.
ind  = dim_names.index('B')

for i in range(ar.shape[ind]):
    print(ar[:,i,:])

But depending on ind the indexing has to change, e.g. for ind = 0 we need ar[i,:,:] or for ind = 2 ar[:,:,i]. Furthermore it should work for an array of any number of dimensions.

A:

There might be a better approach for your problem, but as for the question, you can construct the index dynamically in the loop, i.e. specify the desired dimension of the index and slice.
Slice along first dimension:
ind = 0
​
for i in range(ar.shape[ind]):
    idx = [slice(None)] * ar.ndim             # inintialize the index with the same length 
                                              # as the dimensions
    idx[ind] = i                              # modify the index of the desired dimension
    print(ar[tuple(idx)])

#[[ 8 10]
# [ 9 11]
# [10 12]]
#[[ 9 11]
# [10 12]
# [11 13]]

Slice along second dimension:
ind = 1
​
for i in range(ar.shape[ind]):
    idx = [slice(None)] * ar.ndim
    idx[ind] = i
    print(ar[tuple(idx)])

#[[ 8 10]
# [ 9 11]]
#[[ 9 11]
# [10 12]]
#[[10 12]
# [11 13]]

Slice along third dimension:
ind = 2
​
for i in range(ar.shape[ind]):
    idx = [slice(None)] * ar.ndim
    idx[ind] = i
    print(ar[tuple(idx)])

#[[ 8  9 10]
# [ 9 10 11]]
#[[10 11 12]
# [11 12 13]]

