w3resource

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

NumPy: Broadcasting Exercise-11 with Solution

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:

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

Previous: Numpy Program to divide 2D array by 1D array using Broadcasting.
Next: Python Program to multiply 2D array and Scalar using Broadcasting.

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/numpy-program-to-add-3d-array-and-2d-array-using-broadcasting.php