w3resource

Numpy Program to subtract 1D array from 2D slices of 3D array


Write a NumPy program to subtract a 1D array y of shape (3,) from each 2D slice of 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)
array_3d = np.array([[[ 1,  2,  3,  4],
                      [ 5,  6,  7,  8],
                      [ 9, 10, 11, 12]],

                     [[13, 14, 15, 16],
                      [17, 18, 19, 20],
                      [21, 22, 23, 24]]])

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

# Subtract the 1D array from each 2D slice of the 3D array
# Broadcasting is used here to subtract 1D array from each 2D slice of 3D array
result_array = array_3d - array_1d[:, np.newaxis]

# Display the result
print(result_array)

Output:

[[[ 0  1  2  3]
  [ 3  4  5  6]
  [ 6  7  8  9]]

 [[12 13 14 15]
  [15 16 17 18]
  [18 19 20 21]]]

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 (3,) are initialized.
  • Broadcasting and Subtraction: The 1D array is subtracted from each 2D slice of the 3D array using broadcasting. The 1D array is reshaped to (3, 1) to match the 2D slices' dimensions.
  • Displaying result: The resulting array is printed out.

Python-Numpy Code Editor: