w3resource

Numpy Program to add 1D array to each 2D slice of 3D array using Broadcasting


14. Add 1D Array to Each 2D Slice of 3D Array

Write a Numpy program that adds a 1D array of shape (6,) to each 2D slice of a 3D array of shape (2, 6, 4) using broadcasting.

Sample Solution:

Python Code:

import numpy as np

# Initialize the 3D array of shape (2, 6, 4)
x = 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]],

              [[25, 26, 27, 28],
               [29, 30, 31, 32],
               [33, 34, 35, 36],
               [37, 38, 39, 40],
               [41, 42, 43, 44],
               [45, 46, 47, 48]]])

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

# Add the 1D array to each 2D slice of the 3D array using broadcasting
result_array = x + y[:, np.newaxis]

# Display the result
print(result_array)

Output:

[[[ 2  3  4  5]
  [ 7  8  9 10]
  [12 13 14 15]
  [17 18 19 20]
  [22 23 24 25]
  [27 28 29 30]]

 [[26 27 28 29]
  [31 32 33 34]
  [36 37 38 39]
  [41 42 43 44]
  [46 47 48 49]
  [51 52 53 54]]]

Explanation:

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

For more Practice: Solve these Related Problems:

  • Add a 1D array to each 2D slice of a 3D array using broadcasting and then compute the mean of each modified slice.
  • Create a function that applies a 1D offset to every slice of a 3D array and returns the modified array.
  • Implement a solution that uses np.add with broadcasting to add different 1D arrays to corresponding slices.
  • Test the addition on a 3D array with varying slice values to verify the operation across all slices.

Python-Numpy Code Editor:

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

Previous: Numpy Program to multiply each row of 2D array by 1D array using Broadcasting.
Next: Numpy Program to add arrays of Shapes (2, 1, 3) and (1, 4, 1) using Broadcasting.

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.