Numpy element-wise addition with multiple arrays
Asked Answered
E

3

8

I'd like to know if there is a more efficient/pythonic way to add multiple numpy arrays (2D) rather than:

def sum_multiple_arrays(list_of_arrays):
   a = np.zeros(shape=list_of_arrays[0].shape) #initialize array of 0s
   for array in list_of_arrays:
      a += array
   return a 

Ps: I am aware of np.add() but it works only with 2 arrays.

Exciter answered 9/2, 2021 at 1:18 Comment(2)
np.sum(list_of_arrays, axis=0) should work. Or np.add.reduce(list_of_arrays).Tripletail
Thank you very much. Please let it be an answer so i can acceptExciter
T
14
np.sum(list_of_arrays, axis=0) 

should work. Or

np.add.reduce(list_of_arrays). 
Tripletail answered 9/2, 2021 at 1:29 Comment(0)
N
4

The simplest and most Pythonic solution is simply to use sum(), like so:

sum(list_of_arrays)
Nader answered 25/2, 2023 at 9:29 Comment(3)
doesnt work for more than 2 arrays.Bargello
@DaddyKropotkin Seems to work for me, for example: sum([np.array([0,1]), np.array([1,0]), np.array([1.1, 1.1])])Nader
Surprisingly on NumPy 1.26.4 sum() runs faster than np.sum(..., axis=0) and np.add.reduce() by ~25% (1.4ms compared to 1.8ms) for my list of 5 arrays of ~100000 rows and 5 columns. I have checked again with a list of np.random.sample((100_000, 5)) arrays and same results.Flatiron
N
1

i know the question says numpy, but here's a pure python answer in case someone needs it.

map(sum, zip(a,b)) which returns a generator. you can also do list(map(sum, zip(a,b))) to get a list

Nitriding answered 28/6, 2023 at 22:26 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.