Adding numpy arrays of various shapes

I would like to add two numpy arrays of different shapes, but without translation, and the “missing” values ​​are treated as zeros. Probably the easiest way with an example like

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

or

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

I do not know the form in advance.

I fiddled with np.shape for everyone, trying to find the smallest figure that contains both of them, inserting each into a zero-ed array of this shape, and then adding them. But this seems to be pretty much work, is there an easier way?

Thanks in advance!

edit: “A lot of work” I meant “a lot of work for me” and not for the car, I am looking for elegance, not efficiency: my effort, getting the smallest form, holding them both,

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)

Not really: -/

+5
source share
2 answers

, :

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, , , :

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

np.shape , , , -ed , . , ?

np.shape , , , , , , , " " " -ed " ".

, , resize ( resize, ). :

:...

, :

>>> 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]])
+4

All Articles