Numpy reshape - 自动填充或移除

Numpy reshape - automatic filling or removal

我想找到一个重塑函数,它能够将我的不同维度的数组转换为相同维度的数组。让我解释一下:

import numpy as np
a = np.array([[[1,2,3,3],[1,2,3,3]],[[1,2,3,3],[1,2,3,3]]])
b = np.array([[[1,2,3,3],[1,2,3,3]],[[1,2,3,3],[1,2,3,3]],[[1,2,3,3],[1,2,3,4]]])
c = np.array([[[1,2,3,3],[1,2,3,3]]])

我希望能够使 b,c 个形状等于 a 个形状。但是,np.reshape 会抛出错误,因为如此处所述 (Numpy resize or Numpy reshape) 该函数明确用于处理相同的维度。

我想要该函数的某些版本,如果形状较小,则在第一维的开头添加零,如果形状较大,则删除开头。我的示例将如下所示:

b = np.array([[[1,2,3,3],[1,2,3,3]],[[1,2,3,3],[1,2,3,4]]])
c = np.array([[[0,0,0,0],[0,0,0,0]],[[1,2,3,3],[1,2,3,3]]])

我需要自己编写函数吗?

我会写一个这样的函数:

def align(a,b):
    out = np.zeros_like(a)
    x = min(a.shape[0], b.shape[0])
    out[-x:] = b[-x:]

    return out

输出:

align(a,b)
# array([[[1, 2, 3, 3],
#         [1, 2, 3, 3]],

#        [[1, 2, 3, 3],
#         [1, 2, 3, 4]]])

align(a,c)
# array([[[0, 0, 0, 0],
#         [0, 0, 0, 0]],

#        [[1, 2, 3, 3],
#         [1, 2, 3, 3]]])

这与上面的解决方案类似,但如果较低的维度不匹配也可以工作

def custom_reshape(a, b):
    result = np.zeros_like(a).ravel()
    result[-min(a.size, b.size):] = b.ravel()[-min(a.size, b.size):]
    return result.reshape(a.shape)

custom_reshape(a,b)