NumPy: Divide each row by a vector element

Given a NumPy array, we have to divide each row by a vector element. By Pranit Sharma Last updated : October 08, 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 we are given a multidimensional NumPy array and also, we have a corresponding vector, we need to perform an operation on the NumPy array in such a way that each row is divided by the corresponding vector which means that each element of each row is divided by each element of the vector.

Dividing each row by a vector element

For this purpose, we will simply divide the whole NumPy array with the whole vector. A great way of doing this even for higher dimensional arrays.

Let us understand with the help of an example,

Python program to divide each row by a vector element

# Import counter from collections
from collections import Counter

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([[1,2,3],[2,3,4],[3,4,5]])

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

# Creating a vector
vec = np.array([1,2,3])

# Display original vector
print("Original Vector:\n",vec,"\n")

# Dividing arr by vec
res = arr/vec[:,None]

# Display result


The output of the above program is:

Example: NumPy: Divide each row by a vector element

Python NumPy Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.