w3resource

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

NumPy: Broadcasting Exercise-8 with Solution

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:

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

Previous: Numpy program to Transpose and add arrays.
Next: Numpy Program to reshape and add 1D arrays using 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/numpy-program-to-subtract-1d-array-from-2d-slices-of-3d-array.php