我想添加两个不同形状的 numpy 数组,但不进行广播,而是将“缺失”值视为零。可能最简单的例子是
[1, 2, 3] + [2] -> [3, 2, 3]
或
[1, 2, 3] + [[2], [1]] -> [[3, 2, 3], [1, 0, 0]]
我事先不知道这些形状。
我正在弄乱每个 np.shape 的输出,试图找到包含它们的最小形状,将每个形状嵌入到该形状的零编辑数组中,然后将它们相加。但是看起来工作量比较大,有没有更简单的方法呢?
提前致谢!
编辑:我所说的“大量工作”是指“为我做大量工作”而不是机器,我寻求优雅而不是效率:我努力获得最小的形状来同时容纳它们
def pad(a, b) :
sa, sb = map(np.shape, [a, b])
N = np.max([len(sa),len(sb)])
sap, sbp = map(lambda x : x + (1,)*(N-len(x)), [sa, sb])
sp = np.amax( np.array([ tuple(sap), tuple(sbp) ]), 1)
不漂亮:-/
最佳答案
I'm messing around with the output of np.shape for each, trying to find the smallest shape which holds both of them, embedding each in a zero-ed array of that shape and then adding them. But it seems rather a lot of work, is there an easier way?
获取 np.shape
是微不足道的,找到包含两者的最小形状非常容易,当然添加也是微不足道的,所以唯一“大量工作”的部分是“嵌入”每个都在该形状的零数组中。
是的,您可以通过调用 resize
来消除它方法(或 resize
函数,如果你想制作副本而不是就地更改它们)。正如文档所解释的那样:
Enlarging an array: … missing entries are filled with zeros
例如,如果您静态地知道维度:
>>> a1 = np.array([[1, 2, 3], [4, 5, 6]])
>>> a2 = np.array([[2], [2]])
>>> shape = [max(a.shape[axis] for a in (a1, a2)) for axis in range(2)]
>>> a1.resize(shape)
>>> a2.resize(shape)
>>> print(a1 + a2)
array([[3, 4, 3],
[4, 5, 6]])
关于python - 添加不同形状的 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16180681/