I want to create a function that takes a numpy array, an axis and an index of that axis and returns the array with the index on the specified axis fixed. What I thought is to create a string that change dynamically and then is evaluated as an index slicing in the array (as showed in this answer). I came up with the following function:
import numpy as np def select_slc_ax(arr, slc, axs): dim = len(arr.shape)-1 slc = str(slc) slice_str = ":,"*axs+slc+",:"*(dim-axs) print(slice_str) slice_obj = eval(f'np.s_[{slice_str}]') return arr[slice_obj]
Example
>>> arr = np.array([[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 1, 0], [1, 1, 1], [0, 1, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]], dtype='uint8') >>> select_slc_ax(arr, 2, 1) :,2,: array([[0, 0, 0], [0, 1, 0], [0, 0, 0]], dtype=uint8)
I was wondering if there is a better method to do this.