w3resource

Subtract 1D array from 2D array using NumPy Broadcasting

NumPy: Broadcasting Exercise-2 with Solution

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:

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.



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://198.211.115.131/python-exercises/numpy/subtract-1d-array-from-2d-array-using-numpy-broadcasting.php