w3resource

How to use NumPy Broadcasting to divide 2D arrays by 1D arrays

NumPy: Broadcasting Exercise-17 with Solution

Create a 2D array x of shape (5, 5) and a 1D array y of shape (5,). Write a NumPy program that divides each row of a by b using broadcasting.

Sample Solution:

Python Code:

import numpy as np

# Create a 2D array x of shape (5, 5)
x = np.array([[10, 20, 30, 40, 50],
              [5, 15, 25, 35, 45],
              [1, 2, 3, 4, 5],
              [6, 12, 18, 24, 30],
              [9, 18, 27, 36, 45]])

# Create a 1D array y of shape (5,)
y = np.array([1, 2, 3, 4, 5])

# Divide each row of x by the array y using broadcasting
result = x / y[:, np.newaxis]

print(result)

Output:

[[10.         20.         30.         40.         50.        ]
 [ 2.5         7.5        12.5        17.5        22.5       ]
 [ 0.33333333  0.66666667  1.          1.33333333  1.66666667]
 [ 1.5         3.          4.5         6.          7.5       ]
 [ 1.8         3.6         5.4         7.2         9.        ]]

Explanation:

  • Import NumPy: Import the NumPy library to handle array operations.
  • Create 2D array x: Define a 2D array x with shape (5, 5).
  • Create 1D array y: Define a 1D array y with shape (5,).
  • Broadcasting Division: Use broadcasting to divide each row of x by the corresponding element in y.
  • Print Result: Print the resulting array.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Numpy Program to subtract 1D array from 3D array using Broadcasting.
Next: How to reshape arrays and perform element-wise addition using NumPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/using-numpy-to-divide-2d-arrays-by-1d-arrays-with-broadcasting.php