Вы можете создать кортеж и использовать slice(None)
вместо :
:
def custom_index(arr, position, index):
idx = [slice(None)] * len(arr.shape)
idx[position] = index
return arr[tuple(idx)]
Быстрый тест:
mat = np.random.random((5, 3))
assert np.all(mat[2, :] == custom_index(mat, 0, 2)) # mat[(2, slice(None))]
assert np.all(mat[:, 2] == custom_index(mat, 1, 2)) # mat[(slice(None), 2))]
РЕДАКТИРОВАТЬ: как Указанный в комментарии правильный путь: np.take