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

Daidalos July 31, 2019

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)

Can be used with real numbers as well:

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

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])

Sum elements over array columns

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


Links Site
sum Numpy doc
How to calculate the sum of all columns of a 2D numpy array (efficiently) stackoverflow


Google Ads


Google Ads