我在 python 中有一个二维数组数组,所有这些数组都是 20 行,但列号可变(每列在 80 到 90 之间)。
我想在这些二维数组中迭代添加数字(浮点)值以创建一个最终的二维数组(参见下面的示意图)。
我是 python/numpy 库的新手,发现了一些可能是我正在寻找但似乎无法让它们工作的函数。
连接 docs here说它将添加两个不同大小的矩阵(假设一个轴完全相同,我想?)但我不知道如何迭代地实际执行添加步骤。原因是因为我想在我的循环范围之外初始化一个空的 numpy 数组,所以我可以一遍又一遍地添加它并保存值,但是当我尝试初始化一个数组时:
my_final_matrix = np.array()
它抛出一个错误,在构造函数中没有定义数组。
展平/ reshape docs here减少维度但不添加值。
In short -- how do I iteratively add different-sized matrices in numpy?
请您参考如下方法:
这是一个自动检测所需输出大小的解决方案:
>>> import numpy as np
>>>
# create ragged list
>>> n = 4
>>> ragged = list(map(np.full, np.random.randint(1, 6, (n, 2)), 10**np.arange(n)))
>>>
>>> ragged
[array([[1, 1, 1]]), array([[10, 10],
[10, 10],
[10, 10]]), array([[100],
[100],
[100]]), array([[1000, 1000, 1000, 1000],
[1000, 1000, 1000, 1000]])]
>>>
# find maximum size in each dimension
>>> maxsh = *map(max, zip(*map(np.shape, ragged))),
# allocate result
>>> result = np.zeros(maxsh, dtype=ragged[0].dtype)
# and add
>>> for r in ragged:
... result[(*map(slice, r.shape),)] += r
...
>>> result
array([[1111, 1011, 1001, 1000],
[1110, 1010, 1000, 1000],
[ 110, 10, 0, 0]])
