How to find the sum of rows and columns of a given matrix using Numpy?

PythonNumpyServer Side ProgrammingProgramming

In this problem, we will find the sum of all the rows and all the columns separately. We will use the sum() function for obtaining the sum.

Algorithm

Step 1: Import numpy.
Step 2: Create a numpy matrix of mxn dimension.
Step 3: Obtain the sum of all the rows.
Step 4: Obtain the sum of all the columns.

Example Code

import numpy as np

a = np.matrix('10 20; 30 40')
print("Our matrix: \n", a)

sum_of_rows = np.sum(a, axis = 0)
print("\nSum of all the rows: ", sum_of_rows)

sum_of_cols = np.sum(a, axis = 1)
print("\nSum of all the columns: \n", sum_of_cols)

Output

Our matrix:
 [[10 20]
 [30 40]]
Sum of all the rows:  [[40 60]]
Sum of all the columns:
 [[30]
 [70]]

Explanation

The np.sum() function takes an additional matrix called the 'axis'. Axis takes two values. Either 0 or 1. If axis=0, it tells the sum() function to consider only the rows. If axis = 1, it tells the sum() function to consider only the columns.

raja
Published on 16-Mar-2021 10:27:17
Advertisements