# Sum all the elements in a NumPy array by column or row

NumPy sum calculates the sum of elements in a vector or matrix (array).

import numpy

a1 = numpy.array([1, 2])
a2 = numpy.array([[1, 2], [3, 4]])

s1 = numpy.sum(a1)
s2 = numpy.sum(a2)

print(s1)  # 3
print(s2)  # 10


## Sum all the elements by column or row

import numpy

a = numpy.array([[1, 2, 3], [4, 5, 6]])

b = numpy.sum(a)
c = numpy.sum(a, axis=0)
d = numpy.sum(a, axis=1)

print(b)  # 21
print(c)  # [5 7 9]
print(d)  # [ 6 15]


The axis option means sum "direction". Without that, it simply sums all the elements and that is default. If the axis is 0, it sums each column. If the axis is 1, it sums each row.