Skip to main content
 首页 » 编程设计

python之匹配特定形状的 Numpy 零填充

2025年05月04日16emanlee

我有一个包含数组或不同形状的文件。我想对所有数组进行零填充以匹配最大的形状。最大的形状是 (93,13)。

为了测试这一点,我有以下代码:

testarray = np.ones((41,13)) 

我怎样才能对这个数组进行零填充以匹配 (93,13) 的形状?最终,我怎样才能为数千行做到这一点?

编辑:在评论中找到了解决方案:

for index, array in enumerate(mfcc): 
    testarray = np.zeros((93,13)) 
    for index,row in enumerate(array): 
        for i in range(0,len(row)-1): 
            testarray[index][i]= row[i] 
            mfcc[index] = testarray 

请您参考如下方法:

这是一种使用 np.pad 的方法可以推广到任意目标形状:

def to_shape(a, shape): 
    y_, x_ = shape 
    y, x = a.shape 
    y_pad = (y_-y) 
    x_pad = (x_-x) 
    return np.pad(a,((y_pad//2, y_pad//2 + y_pad%2),  
                     (x_pad//2, x_pad//2 + x_pad%2)), 
                  mode = 'constant') 

对于建议的示例:

a = np.ones((41,13)) 
shape = [93, 13] 
to_shape(a, shape).shape 
# (93, 13) 

让我们检查另一个例子:

shape = [100, 121] 
to_shape(a, shape).shape 
# (100, 121) 

时间

def florian(array, shape): 
    #print(array) 
    testarray = np.zeros(shape) 
    for index,row in enumerate(array): 
        for i in range(0,len(row)-1): 
            testarray[index][i]= row[i] 
 
def to_shape(a, shape): 
    y_, x_ = shape 
    y, x = a.shape 
    y_pad = (y_-y) 
    x_pad = (x_-x) 
    return np.pad(a,((y_pad//2, y_pad//2 + y_pad%2),  
                     (x_pad//2, x_pad//2 + x_pad%2)), 
                  mode = 'constant') 
 
a = np.ones((500, 500)) 
shape = [1000, 1103] 
 
%timeit florian(a, shape) 
# 101 ms ± 5.12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) 
 
%timeit to_shape(a, shape) 
# 19.8 ms ± 318 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)