NumPy: Divide row by row sum

Learn, how to divide row by sum of the numpy array? Submitted by Pranit Sharma, on January 24, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Problem statement

Suppose that we are given a NumPy array and we need to divide this NumPy array's row by the sum of all the values in that row.

Dividing row by row sum

The easiest approach to solve this problem is to divide the array by the sum of the specified row by defining the axis as 1 and slice it by using None.

Let us understand with the help of an example,

Python code to divide row by row sum

# Import numpy
import numpy as np

# Import math
import math

# Creating a numpy array
arr = np.array([[3., 4.],[5., 6.],[7., 8.]])

# Display original array
print("Original array:\n",arr,"\n")

# dividing the row by its sum
res = arr/arr.sum(axis=1)[:,None]

# Display result
print("Result:\n",res,"\n")

Output

Example: NumPy: Divide row by row sum

Python NumPy Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.