39

If I have two numpy arrays of different sizes, how can I superimpose them.

a = numpy([0, 10, 20, 30])
b = numpy([20, 30, 40, 50, 60, 70])

What is the cleanest way to add these two vectors to produce a new vector (20, 40, 60, 80, 60, 70)?

This is my generic question. For background, I am specifically applying a Green's transform function and need to superimpose the results for each time step in the evaulation unto the responses previously accumulated.

sykora
  • 96,888
  • 11
  • 64
  • 71
tnt
  • 3,411
  • 5
  • 24
  • 23
  • Just a curiosity, why do you prefer creating a new vector instead of using a single (always the same) target vector to superimpose each iteration? I think this could be more memory efficient. – heltonbiker Oct 25 '11 at 15:54

3 Answers3

37

This could be what you are looking for

if len(a) < len(b):
    c = b.copy()
    c[:len(a)] += a
else:
    c = a.copy()
    c[:len(b)] += b

basically you copy the longer one and then add in-place the shorter one

6502
  • 112,025
  • 15
  • 165
  • 265
  • How to do it if the arrays are inside an array ? – TheTechGuy Jan 07 '19 at 19:03
  • What do you mean with "inside an array"? if you want a new fresh array when the sum the code stays the same, if instead you want to do the addition in-place then just work on the appropriate slice (e.g. `m[i][j][:len(a)] += a`). – 6502 Jan 07 '19 at 21:38
17

If you know that b is higher dimension, then:

>>> a.resize(b.shape)
>>> c = a+b

is all you need.

Eric Wilson
  • 57,719
  • 77
  • 200
  • 270
  • 5
    That will only work if there is no other reference to `a`. and many times there are internal references, you don't know of. – steffen Jun 28 '18 at 15:39
2

Very similar to the one above, but a little more compact:

l = sorted((a, b), key=len)
c = l[1].copy()
c[:len(l[0])] += l[0]
Tobia Marcucci
  • 204
  • 1
  • 7