Numpy Program to add 1D array to each 2D slice of 3D array using Broadcasting
NumPy: Broadcasting Exercise-14 with Solution
Write a Numpy program that adds a 1D array of shape (6,) to each 2D slice of a 3D array of shape (2, 6, 4) using broadcasting.
Sample Solution:
Python Code:
import numpy as np
# Initialize the 3D array of shape (2, 6, 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]],
[[25, 26, 27, 28],
[29, 30, 31, 32],
[33, 34, 35, 36],
[37, 38, 39, 40],
[41, 42, 43, 44],
[45, 46, 47, 48]]])
# Initialize the 1D array of shape (6,)
y = np.array([1, 2, 3, 4, 5, 6])
# Add the 1D array to each 2D slice of the 3D array using broadcasting
result_array = x + y[:, np.newaxis]
# Display the result
print(result_array)
Output:
[[[ 2 3 4 5] [ 7 8 9 10] [12 13 14 15] [17 18 19 20] [22 23 24 25] [27 28 29 30]] [[26 27 28 29] [31 32 33 34] [36 37 38 39] [41 42 43 44] [46 47 48 49] [51 52 53 54]]]
Explanation:
- Importing numpy: We first import the numpy library for array manipulations.
- Initializing arrays: A 3D array of shape (2, 6, 4) and a 1D array of shape (6,) are initialized.
- Broadcasting and Addition: The 1D array is broadcasted and added to each 2D slice of the 3D array.
- 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 multiply each row of 2D array by 1D array using Broadcasting.
Next: Numpy Program to add arrays of Shapes (2, 1, 3) and (1, 4, 1) using Broadcasting.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://198.211.115.131/python-exercises/numpy/numpy-program-to-add-1d-array-to-each-2d-slice-of-3d-array-using-broadcasting.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics