w3resource

Numpy Program to divide 2D array by 1D array using Broadcasting


Write a NumPy program that performs element-wise division of a 2D array x of shape (6, 4) by a 1D array y of shape (4,) using broadcasting.

Sample Solution:

Python Code:

import numpy as np

# Initialize the 2D array of shape (6, 4)
x = np.array([[12, 24, 36, 48],
              [10, 20, 30, 40],
              [8, 16, 24, 32],
              [6, 12, 18, 24],
              [4, 8, 12, 16],
              [2, 4, 6, 8]])

# Initialize the 1D array of shape (4,)
y = np.array([2, 4, 6, 8])

# Perform element-wise division using broadcasting
result_array = x / y

# Display the result
print(result_array)

Output:

[[6. 6. 6. 6.]
 [5. 5. 5. 5.]
 [4. 4. 4. 4.]
 [3. 3. 3. 3.]
 [2. 2. 2. 2.]
 [1. 1. 1. 1.]]

Explanation:

  • Importing numpy: We first import the numpy library for array manipulations.
  • Initializing arrays: A 2D array of shape (6, 4) and a 1D array of shape (4,) are initialized.
  • Broadcasting and Division: Element-wise division is performed using broadcasting between the 2D array and the 1D array.
  • Displaying result: The resulting array is printed out.

Python-Numpy Code Editor: