如何得到numpy数组的最大二维切片



我有一个3d numpy数组,其中尺寸不同。我想画一个平行于最大的二维空间和最小的二维空间中间的切片。我怎样才能拿到切片?

。如果我的原始数据是

np.ones(3*4*5).reshape(3,4,5)

我想获得数据集

np.ones(3*4*5).reshape(3,4,5)[1,:,:]

是第一个维度的一半因为它是最小的其他两个维度因为它们更大

您可以使用np.rollaxis来完成这样的任务,这将适用于任何多维数组,如-

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

最新更新