w3resource

Numpy Program to add 3D array and 2D array using Broadcasting


Given a 3D array x of shape (2, 3, 4) and a 2D array y of shape (3, 4). Write a NumPy program to add them using broadcasting.

Sample Solution:

Python Code:

import numpy as np

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

# Initialize the 2D array of shape (3, 4)
y = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12]])

# Add the 3D array and the 2D array using broadcasting
result_array = x + y

# Display the result
print(result_array)

Output:

[[[ 2  4  6  8]
  [10 12 14 16]
  [18 20 22 24]]

 [[14 16 18 20]
  [22 24 26 28]
  [30 32 34 36]]]

Explanation:

  • Importing numpy: We first import the numpy library for array manipulations.
  • Initializing arrays: A 3D array of shape (2, 3, 4) and a 2D array of shape (3, 4) are initialized.
  • Broadcasting and Addition: The 2D array is broadcasted across the 3D array, and element-wise addition is performed.
  • Displaying result: The resulting array is printed out.

Python-Numpy Code Editor: