添加不同形状的numpy数组 [英] adding numpy arrays of differing shapes

查看:244
本文介绍了添加不同形状的numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加两个不同形状的numpy数组,但不进行广播,而是将缺失"值视为零.像这样的示例可能最简单

I'd like to add two numpy arrays of different shapes, but without broadcasting, rather the "missing" values are treated as zeros. Probably easiest with an example like

[1, 2, 3] + [2] -> [3, 2, 3]

[1, 2, 3] + [[2], [1]] -> [[3, 2, 3], [1, 0, 0]]

我事先不知道形状.

我正在弄乱每个np.shape的输出,试图找到容纳两个形状的最小形状,将每个形状嵌入到该形状的零位数组中,然后添加它们.但这似乎需要大量工作,是否有更简单的方法?

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?

提前谢谢!

很多工作"我的意思是很多工作对我来说"而不是对机器而言,我追求的是优雅而不是效率:我努力使两者都保持最小的形状是

edit: by "a lot of work" I meant "a lot of work for me" rather than for the machine, I seek elegance rather than efficiency: my effort getting the smallest shape holding them both is

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)

不漂亮:-/

推荐答案

这是我能想到的最好的方法:

This is the best I could come up with:

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

如果您知道期望结果有多少个维度,可以稍微清理一下for循环,例如:

You can clean up the for loop a little if you know how many dimensions you expect on result, something like:

for a in args:
    i, j = a.shape
    result[:i, :j] += a

这篇关于添加不同形状的numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆