Sum of Columns of a Matrix in Numpy

  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

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 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.]
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.