w3resource

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


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.

Python-Numpy Code Editor: