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

In NumPy, you can calculate the sum of rows and columns of a matrix using the np.sum() function with the axis parameter. This is useful for data analysis and mathematical computations.

Syntax

numpy.sum(array, axis=None)

Parameters:

  • array − Input matrix or array
  • axis − 0 for column-wise sum, 1 for row-wise sum

Example

Let's create a matrix and find the sum of rows and columns ?

import numpy as np

# Create a 2x2 matrix
matrix = np.array([[10, 20], 
                   [30, 40]])
print("Our matrix:")
print(matrix)

# Sum of columns (axis=0)
sum_of_columns = np.sum(matrix, axis=0)
print("\nSum of columns:", sum_of_columns)

# Sum of rows (axis=1) 
sum_of_rows = np.sum(matrix, axis=1)
print("\nSum of rows:", sum_of_rows)
Our matrix:
[[10 20]
 [30 40]]

Sum of columns: [40 60]

Sum of rows: [30 70]

How It Works

The axis parameter determines the direction of summation:

  • axis=0 − Sums along columns (adds elements vertically)
  • axis=1 − Sums along rows (adds elements horizontally)
Matrix Sum Operations 10 20 30 40 40 60 30 70 axis=0 (columns) axis=1 (rows)

Working with Larger Matrices

Let's see how it works with a 3x3 matrix ?

import numpy as np

# Create a 3x3 matrix
data = np.array([[1, 2, 3],
                 [4, 5, 6], 
                 [7, 8, 9]])

print("3x3 Matrix:")
print(data)

print("\nColumn sums (axis=0):", np.sum(data, axis=0))
print("Row sums (axis=1):", np.sum(data, axis=1))
print("Total sum (no axis):", np.sum(data))
3x3 Matrix:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Column sums (axis=0): [12 15 18]
Row sums (axis=1): [ 6 15 24]
Total sum (no axis): 45

Comparison

Parameter Operation Result Shape
axis=0 Sum along columns (n_cols,)
axis=1 Sum along rows (n_rows,)
No axis Sum all elements Single value

Conclusion

Use np.sum(matrix, axis=0) for column sums and np.sum(matrix, axis=1) for row sums. The axis parameter determines the direction of the summation operation.

Updated on: 2026-03-25T17:54:30+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements