7

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.

heresthebuzz
  • 678
  • 7
  • 21

3 Answers3

11
np.sum(list_of_arrays, axis=0) 

should work. Or

np.add.reduce(list_of_arrays). 
hpaulj
  • 221,503
  • 14
  • 230
  • 353
2

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

sum(list_of_arrays)
Moot
  • 2,195
  • 2
  • 17
  • 14
0

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

Nande
  • 409
  • 1
  • 6
  • 11