w3resource

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


17. Divide Each Row of 2D Array by 1D Array

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.

For more Practice: Solve these Related Problems:

  • Create a function that divides each row of a 2D array by a corresponding element in a 1D array and returns the result.
  • Implement a solution that normalizes each row of a 2D array by its maximum value using broadcasting.
  • Test the division on a 2D array with both positive and negative values to ensure proper broadcasting behavior.
  • Compare the result of row-wise division using broadcasting with that obtained by manually looping through the rows.

Go to:


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

Python-Numpy Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.