How to add / sum the elements of an array in python ?

Published: July 31, 2019

DMCA.com Protection Status

To sum the elements of an array in python, a solution is to use the numpy function sum, example:

Sum all elements

 >>> import numpy as np
 >>> M = np.array([[1, 2], [3, 4]])
 >>> M
 array([[1, 2],
   [3, 4]])
 >>> np.sum(M)
 10

Can be used with real numbers as well:

  >>> M = np.array([[1.0, 2.0], [3.1, 4.4]])
  >>> np.sum(M)
  10.5

Sum elements over array lines

>>> np.sum(M, axis=0)
array([4, 6])

It is also possible to select a specific column and do the sum, example:

on peut aussi choisir une colonne donnée:

>>> np.sum(M[:,1])
6

Sum elements over array columns

>>> np.sum(M, axis=1)
array([3, 7])

References