我想添加两个不同形状的numpy数组,但没有广播,而是将"缺失"值视为零.像一个例子可能最简单
[1, 2, 3] + [2] -> [3, 2, 3]
Run Code Online (Sandbox Code Playgroud)
要么
[1, 2, 3] + [[2], [1]] -> [[3, 2, 3], [1, 0, 0]]
Run Code Online (Sandbox Code Playgroud)
我事先不知道形状.
我正在弄乱每个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)
Run Code Online (Sandbox Code Playgroud)
不漂亮 :-/
这是我能想到的最好的:
import numpy as np
def magic_add(*args):
n = max(a.ndim for a in args)
args = [a.reshape((n - a.ndim)*(1,) + a.shape) for a in args]
shape = np.max([a.shape for a in args], 0)
result = np.zeros(shape)
for a in args:
idx = tuple(slice(i) for i in a.shape)
result[idx] += a
return result
Run Code Online (Sandbox Code Playgroud)
如果您知道期望结果有多少个维度,则可以稍微清理一下 for 循环,例如:
for a in args:
i, j = a.shape
result[:i, :j] += a
Run Code Online (Sandbox Code Playgroud)