Skip to main content
 首页 » 编程设计

python之返回最后两个维度的 numpy 切片

2024年10月25日11小虾米

基本上,我正在寻找一种函数或语法,使我能够获得具有任意维数的 n 维 numpy 数组的最后两个维度的第一个“切片”。

我可以这样做,但它太难看了,如果有人发送一个 6d 数组怎么办?必须有一个 numpy 函数,如扩展为 0,0,0,... 的椭圆,而不是 :,:,:,...

data_2d = np.ones(5**2).reshape(5,5) 
data_3d = np.ones(5**3).reshape(5,5,5) 
data_4d = np.ones(5**4).reshape(5,5,5,5) 
 
def get_last2d(data): 
    if data.ndim == 2: 
        return data[:] 
    if data.ndim == 3: 
        return data[0, :] 
    if data.ndim == 4: 
        return data[0, 0, :] 
 
np.array_equal(get_last2d(data_3d), get_last2d(data_4d)) 

谢谢, 科林

请您参考如下方法:

这个怎么样,

def get_last2d(data): 
    if data.ndim <= 2: 
        return data 
    slc = [0] * (data.ndim - 2) 
    slc += [slice(None), slice(None)] 
    return data[slc]