Subtract 1D array from 2D array using NumPy Broadcasting
Write a NumPy program that creates a 2D array x of shape (3, 4) and a 1D array y of shape (4,). Subtract y from each row of x using broadcasting.
Sample Solution:
Python Code:
# Import the NumPy library
import numpy as np
# Create a 2D array x with shape (3, 4)
x = np.array([[5, 6, 7, 8], [1, 2, 3, 4], [9, 10, 11, 12]])
# Create a 1D array y with shape (4,)
y = np.array([1, 2, 3, 4])
# Subtract y from each row of x using broadcasting
result = x - y
# 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: [[ 5 6 7 8] [ 1 2 3 4] [ 9 10 11 12]] 1D Array y: [1 2 3 4] Result of x - y: [[4 4 4 4] [0 0 0 0] [8 8 8 8]]
Explanation:
- Import NumPy library: This step imports the NumPy library, essential for numerical operations.
- Create a 2D array x: We use np.array to create a 2D array x with shape (3, 4) and elements [[5, 6, 7, 8], [1, 2, 3, 4], [9, 10, 11, 12]].
- Create a 1D array y: We use np.array to create a 1D array y with shape (4,) and elements [1, 2, 3, 4].
- Subtract y from each row of x using broadcasting: NumPy automatically adjusts the shape of y to match each row of x and performs element-wise subtraction.
- Print the original arrays and the result: This step prints the original 2D array x, the 1D array y, and the result of the subtraction.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics