w3resource

How to use NumPy Broadcasting to add 3D and 2D arrays?


Write a NumPy program to create a 3D array x of shape (3, 1, 5) and a 2D array y of shape (3, 5). Add x and y using broadcasting.

Sample Solution:

Python Code:

import numpy as np

# Create a 3D array x of shape (3, 1, 5)
x = np.array([[[1, 2, 3, 4, 5]],
              [[6, 7, 8, 9, 10]],
              [[11, 12, 13, 14, 15]]])

# Create a 2D array y of shape (3, 5)
y = np.array([[10, 20, 30, 40, 50],
              [15, 25, 35, 45, 55],
              [20, 30, 40, 50, 60]])

# Add x and y using broadcasting
result = x + y[:, np.newaxis, :]

print(result)

Output:

[[[11 22 33 44 55]]

 [[21 32 43 54 65]]

 [[31 42 53 64 75]]]

Explanation:

  • Import NumPy: Import the NumPy library to handle array operations.
  • Create 3D array x: Define a 3D array x with shape (3, 1, 5).
  • Create 2D array y: Define a 2D array y with shape (3, 5).
  • Broadcasting Addition: Add arrays x and y using broadcasting by expanding the dimensions of y to match x.
  • Print Result: Print the resulting array.

Python-Numpy Code Editor: