Divide columns of 2D array by 1D array using NumPy Broadcasting
NumPy: Broadcasting Exercise-6 with Solution
Write a NumPy program that divides each column of a 2D array x of shape (4, 3) by a 1D array y of shape (4,) using broadcasting.
Sample Solution:
Python Code:
# Import the NumPy library
import numpy as np
# Create a 2D array x with shape (4, 3)
x = np.array([[8, 16, 24],
[2, 4, 6],
[12, 24, 36],
[4, 8, 12]])
# Create a 1D array y with shape (4,)
y = np.array([2, 2, 3, 4])
# Reshape y to be a column vector (4, 1) for broadcasting
y_reshaped = y.reshape(4, 1)
# Divide each column of x by y using broadcasting
result = x / y_reshaped
# Print the original arrays and the result
print("2D Array x:\n", x)
print("1D Array y:\n", y)
print("Result of x / y:\n", result)
Output:
2D Array x: [[ 8 16 24] [ 2 4 6] [12 24 36] [ 4 8 12]] 1D Array y: [2 2 3 4] Result of x / y: [[ 4. 8. 12.] [ 1. 2. 3.] [ 4. 8. 12.] [ 1. 2. 3.]]
Explanation:
- Import the NumPy library: This step imports the NumPy library, essential for numerical operations.
- Create a 2D array x with shape (4, 3): We use np.array to create a 2D array x with the specified shape and elements.
- Create a 1D array y with shape (4,): We use np.array to create a 1D array y with the specified shape and elements.
- Reshape y to be a column vector (4, 1) for broadcasting: We reshape y to make it compatible for broadcasting with x by changing its shape to (4, 1).
- Divide each column of x by y using broadcasting: NumPy automatically applies broadcasting to divide each element in the columns of x by the corresponding element in y.
- Print the original arrays and the result: This step prints the original 2D array x, the 1D array y, and the result of the division.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Element-wise multiplication with reshaped arrays using NumPy.
Next: Numpy program to Transpose and add arrays.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://198.211.115.131/python-exercises/numpy/divide-columns-of-2d-array-by-1d-array-using-numpy-broadcasting.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics