w3resource

Subtract 1D array from 2D array using NumPy Broadcasting


2. Row-wise Subtraction Using 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.

For more Practice: Solve these Related Problems:

  • Create a 2D array and subtract a 1D array from each row by reshaping the 1D array appropriately.
  • Implement a function that subtracts the mean of each row from the row itself using broadcasting.
  • Write a solution that subtracts a 1D array from each row of a 2D array and then computes the absolute differences.
  • Test row-wise subtraction on arrays with negative values to ensure the broadcasting behaves correctly.

Python-Numpy Code Editor:

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

Previous: Perform element-wise addition with NumPy Broadcasting.
Next: Multiply 3D array by 1D array using NumPy Broadcasting.

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.