How to calculate sum of columns and rows in Numpy?

How to calculate the sum of columns and rows in the Numpy Python library? Let’s find out in the python tutorial below.
numpy sum of columns

In Numpy, you can quickly sum columns and rows of your array.

Example of numpy sum

To calculate the sum of array columns, specify the axis parameter as 0.

import numpy as np

my_array = np.array([[1, 2, 3],
                    [4, 5, 6],
                    [7, 8, 9]])
print(my_array)
print("Sum of columns equals: ", np.sum(my_array, 0))

numpy sum of columns

Similarly, to sum up rows, specify the axis parameter as 1.

import numpy as np

my_array = np.array([[1, 2, 3],
                    [4, 5, 6],
                    [7, 8, 9]])
print(my_array)
print("Sum of rows equals: ", np.sum(my_array, 1))

numpy sum of rows

To sum up all elements in the array, omit the axis parameter.

import numpy as np

my_array = np.array([[1, 2, 3],
                    [4, 5, 6],
                    [7, 8, 9]])
print(my_array)
print("Sum of every elements of your array equals: ", np.sum(my_array))

numpy sum of array python

See also  Ultimate tutorial on how to round in Numpy