w3resource

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


19. Add 3D Array and 2D Array with Broadcasting

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.

For more Practice: Solve these Related Problems:

  • Create a 3D array of shape (3,1,5) and a 2D array of shape (3,5); add them using broadcasting and verify the output shape.
  • Implement a function that converts a 2D array into a 3D array by adding a new axis and then performs element-wise addition.
  • Test the addition on arrays with varying dimensions and check that the broadcasted addition matches the expected mathematical result.
  • Combine the addition with an operation that computes the sum across the new axis to check consistency.

Go to:


Previous: How to reshape arrays and perform element-wise addition using NumPy?
Next: How to multiply columns of a 2D array by a 1D array using NumPy?

Python-Numpy Code Editor:

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

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.