Numpy Program to subtract 1D array from 3D array using Broadcasting
NumPy: Broadcasting Exercise-16 with Solution
Write a NumPy program to subtract a 1D array y of shape (4,) from a 3D array x of shape (2, 3, 4) using broadcasting.
Sample Solution:
Python Code:
import numpy as np
# Initialize the 3D array of shape (2, 3, 4)
x = np.array([[[10, 20, 30, 40],
[50, 60, 70, 80],
[90, 100, 110, 120]],
[[130, 140, 150, 160],
[170, 180, 190, 200],
[210, 220, 230, 240]]])
# Initialize the 1D array of shape (4,)
y = np.array([1, 2, 3, 4])
# Subtract the 1D array from the 3D array using broadcasting
result_array = x - y
# Display the result
print(result_array)
Output:
[[[ 9 18 27 36] [ 49 58 67 76] [ 89 98 107 116]] [[129 138 147 156] [169 178 187 196] [209 218 227 236]]]
Explanation:
- Importing numpy: We first import the numpy library for array manipulations.
- Initializing arrays: A 3D array of shape (2, 3, 4) and a 1D array of shape (4,) are initialized.
- Broadcasting and Subtraction: The 1D array is broadcasted and subtracted from 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 add arrays of Shapes (2, 1, 3) and (1, 4, 1) using Broadcasting.
Next: How to use NumPy Broadcasting to divide 2D arrays by 1D arrays.
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://www.w3resource.com/python-exercises/numpy/numpy-program-to-subtract-1d-array-from-3d-array-using-broadcasting.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics