- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find the sum of rows and columns of a given matrix using Numpy?
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.
- Related Articles
- Finding the number of rows and columns in a given matrix using Numpy
- How to find the sum of all elements of a given matrix using Numpy?
- How to find the sum of rows, columns, and total in a matrix in R?
- Program to find matrix for which rows and columns holding sum of behind rows and columns in Python
- How to multiply a matrix columns and rows with the same matrix rows and columns in R?
- How to delete different rows and columns of a matrix using a single line code in R?
- C program to sort all columns and rows of matrix
- How to shuffle columns or rows of matrix in PyTorch?
- How to create a subset of rows or columns of a matrix in R?
- How to divide matrix rows by number of columns in R?
- How to find the sum of rows of a column based on multiple columns in R data frame?
- How to find the sum of rows of a column based on multiple columns in R’s data.table object?
- Find the Pair with Given Sum in a Matrix using C++
- Find the Kth Smallest Sum of a Matrix With Sorted Rows in C++
- Generate a Vandermonde matrix and set the number of columns in the output in Numpy

Advertisements