w3resource

Numpy Program to subtract 1D array from 3D array using Broadcasting


16. Subtract 1D Array from 3D Array

Write a NumPy program to subtract a 1D array y of shape (4,) from a 3D array x of shape (2, 3, 4) using broadcasting.

Sample Solution:

Python Code:

import numpy as np

# Initialize the 3D array of shape (2, 3, 4)
x = np.array([[[10, 20, 30, 40],
               [50, 60, 70, 80],
               [90, 100, 110, 120]],

              [[130, 140, 150, 160],
               [170, 180, 190, 200],
               [210, 220, 230, 240]]])

# Initialize the 1D array of shape (4,)
y = np.array([1, 2, 3, 4])

# Subtract the 1D array from the 3D array using broadcasting
result_array = x - y

# Display the result
print(result_array)

Output:

[[[  9  18  27  36]
  [ 49  58  67  76]
  [ 89  98 107 116]]

 [[129 138 147 156]
  [169 178 187 196]
  [209 218 227 236]]]

Explanation:

  • Importing numpy: We first import the numpy library for array manipulations.
  • Initializing arrays: A 3D array of shape (2, 3, 4) and a 1D array of shape (4,) are initialized.
  • Broadcasting and Subtraction: The 1D array is broadcasted and subtracted from each 2D slice of the 3D array.
  • Displaying result: The resulting array is printed out.

For more Practice: Solve these Related Problems:

  • Subtract a 1D array from each slice of a 3D array using broadcasting, and then compute the absolute differences.
  • Create a function that applies a 1D offset to a 3D array and returns both the modified array and the offset used.
  • Implement a solution that subtracts a normalized 1D array from a 3D array and compares the result with the original.
  • Test the function on a 3D array with random values to ensure that broadcasting correctly subtracts the 1D array from each slice.

Python-Numpy Code Editor:

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

Previous: Numpy Program to add arrays of Shapes (2, 1, 3) and (1, 4, 1) using Broadcasting.
Next: How to use NumPy Broadcasting to divide 2D arrays by 1D arrays.

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.