用numpy填充矩阵使高度相等

2024-09-29 19:12:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个矩阵的列表,其中一些矩阵的高度要比其他矩阵大(.shape[0]),我想让它们的高度相等。因此,我想找出最大矩阵的高度,并用不同的矩阵来增加矩阵的其余部分,从而使AMTIX的内容保持在中间。(如果差值不相等,则在底部比顶部多加一行。到目前为止我的代码是:

def equalize_heights(matrices,maxHeight):
    newMatrices = []
    matricesNum = len(matrices)
    for i in xrange(matricesNum):
        matrixHeight = matrices[i].shape[0]
        if (matrixHeight == maxHeight):
            newMatrices.append(matrices[i])
        else:
            addToTop = (maxHeight-matrixHeight)/2
            addToBottom = (maxHeight-matrixHeight)/2 +((maxHeight-matrixHeight)%2)

现在,没有最大矩阵高的矩阵应该在martrix的顶部添加“addToTop”行(填充iwth 0的行),在底部添加“addtobotom”行。在

我想我应该用数字键盘但我不明白到底是怎么回事。在


Tags: 代码内容列表高度def矩阵shapematrices
1条回答
网友
1楼 · 发布于 2024-09-29 19:12:36

请记住np.pad垫在每个维度上,而不仅仅是高度。考虑改用np.concatenate。另外请注意,您不需要通过最大高度-您的函数可以自己计算。在

例如:

import numpy as np
matrices = [np.array([[1,2], [1,2]]), np.array([[1,2], [1,2], [1,2]])]
def equalize_heights(matrices):
    max_height = matrices[0].shape[0]

    for matrix in matrices[1:]:
        max_height = max(max_height, matrix.shape[0])

    for idx, matrix in enumerate(matrices):
        matrices[idx] = np.concatenate((
            matrix,
            np.zeros((max_height - matrix.shape[0], matrix.shape[1]))
            ))

请注意,这不会使矩阵以您想要的方式居中,但这应该不会太困难。(在元组中放入三个数组,而不是两个数组。在

相关问题 更多 >

    热门问题