numpymatrixnumpy-ndarraynumpy-ufunc

Numpy element-wise addition with multiple arrays


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.


Solution

  • np.sum(list_of_arrays, axis=0) 
    

    should work. Or

    np.add.reduce(list_of_arrays)