向numpy数组中添加值以使它们具有相等的形状

2024-06-06 07:02:38 发布

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

我有一个叫做“MEL”的numpy数组,形状是(94824,)。你知道吗

这些值包含不同形状的数组,例如(99,13)、(54,13)(87,13)。我想用零填充小于(99,13)的数组,甚至是更好的数组的平均值。你知道吗

MEL = numpy.ndarray and
for i in MEL: i = <class 'numpy.ndarray'> (i.shape = 99, 13) except for the ones that need to be filled
for j in i: j = <class 'numpy.ndarray'>

到目前为止,我有一个:

max_len = np.max([len(a) for a in MEL])
for i in MEL:
    i = np.asarray([np.pad(a, (0, max_len - len(a)), 'constant', constant_values=0) for a in i])

但形状保持不变。有什么建议吗?你知道吗


Tags: andinnumpyforlennp数组max
1条回答
网友
1楼 · 发布于 2024-06-06 07:02:38

根据我对你问题的理解,MEL是一个包含94824个不同形状的二维数组的列表。您希望返回形状与最大数组相同但填充为0的数组。你知道吗

我想最简单的方法是创建具有适当形状的新数组,并用以前的数组填充它们。一个小例子是:

max_dim = [np.max([a.shape[0] for a in MEL]), np.max([a.shape[1] for a in MEL])]
new_MEL = []
for a in MEL:
    temp = np.zeros((max_dim[0], max_dim[1]))
    temp[:a.shape[0], :a.shape[1]] = a
    new_MEL.append(temp)

相关问题 更多 >