w3resource

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


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.

Python-Numpy Code Editor: