How to Sum of Columns of a Matrix in NumPy

Manav Narula Feb 02, 2024
  1. Use the numpy.sum() Function to Find the Sum of Columns of a Matrix in Python
  2. Use the numpy.einsum() Function to Find the Sum of Columns of a Matrix in Python
  3. Use the numpy.dot() Function to Find the Sum of Columns of a Matrix in Python
How to Sum of Columns of a Matrix in NumPy

This tutorial will introduce how to find the sum of elements along a column in NumPy.

We will calculate the sum of the following matrix.

import numpy as np

a = np.arange(12).reshape(4, 3)
print(a)

Output:

[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]

Use the numpy.sum() Function to Find the Sum of Columns of a Matrix in Python

The sum() function calculates the sum of all elements in an array over the specified axis. If we specify the axis as 0, then it calculates the sum over columns in a matrix.

The following code explains this.

import numpy as np

a = np.arange(12).reshape(4, 3)
s = np.sum(a, axis=0)
print(s)

Output:

[18 22 26]

This method is the most used and fastest of all the methods discussed in this tutorial.

Use the numpy.einsum() Function to Find the Sum of Columns of a Matrix in Python

The einsum() is a helpful yet complicated function in NumPy. It is difficult to explain because it can find the sum in various ways depending on the condition. We can use it to calculate the sum of columns of a matrix, as shown below.

import numpy as np

a = np.arange(12).reshape(4, 3)
s = np.einsum("ij->j", a)
print(s)

Output:

[18 22 26]

The ij->j is the subscript of the function that is used to specify that we need to calculate the sum of the array columns.

Use the numpy.dot() Function to Find the Sum of Columns of a Matrix in Python

It is an irrelevant method, but it still should be known to understand the vast use of the numpy.dot() function. If we calculate the dot product of the 2-D array with a single row array containing only 1, we get the sum of the columns of this matrix.

The following code implements this.

import numpy as np

a = np.arange(12).reshape(4, 3)
s = np.dot(a.T, np.ones(a.shape[0]))
print(s)

Output:

[18. 22. 26.]
Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn