w3resource logo
Python Exercises

Python NumPy: Divide each row by a vector element

Python NumPy: Array Object Exercise-96 with Solution

Write a Python program to divide each row by a vector element.

Sample Solution:-

Python Code:

import numpy as np
x = np.array([[20,20,20],[30,30,30],[40,40,40]])
print("Original array:")
print(x)
v = np.array([20,30,40])
print("Vector:")
print(v)
print(x / v[:,None])

Sample Output:

Original array:                                                        
[[20 20 20]                                                            
 [30 30 30]                                                            
 [40 40 40]]                                                           
Vector:                                                                
[20 30 40]                                                             
[[ 1.  1.  1.]                                                         
 [ 1.  1.  1.]                                                         
 [ 1.  1.  1.]]

Python Code Editor:

import numpy as np
x = np.array([[20,20,20],[30,30,30],[40,40,40]])
print("Original array:")
print(x)
v = np.array([20,30,40])
print("Vector:")
print(v)
print(x / v[:,None])

Improve this sample solution and post your code through Disqus