w3resource

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

NumPy: Broadcasting Exercise-10 with Solution

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:

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

Previous: Numpy Program to reshape and add 1D arrays using Broadcasting.
Next: Numpy Program to add 3D array and 2D array using Broadcasting.

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://www.w3resource.com/python-exercises/numpy/numpy-program-to-divide-2d-array-by-1d-array-using-broadcasting.php