w3resource

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

NumPy: Broadcasting Exercise-19 with Solution

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:

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

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?

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/using-numpy-broadcasting-to-add-3d-and-2d-arrays.php