您可以使用np.rollaxis
對於這樣的任務,這將適用於任何多維ndarray,像這樣 -
def ndim_largest_slice(arr):
shp = arr.shape
return np.rollaxis(arr, np.argmin(shp), 0)[shp[np.argmin(shp)]/2]
樣品試驗 -
In [511]: arr = np.random.rand(6,7,6,3,4,5)
In [512]: np.allclose(ndim_largest_slice(arr),arr[:,:,:,1,:,:])
Out[512]: True
In [513]: arr = np.random.rand(6,7,6,4,5,5)
In [514]: np.allclose(ndim_largest_slice(arr),arr[:,:,:,2,:,:])
Out[514]: True
In [515]: arr = np.random.rand(3,4,5)
In [516]: np.allclose(ndim_largest_slice(arr),arr[1,:,:])
Out[516]: True