Add Scalar to 2D array using NumPy Broadcasting
NumPy: Broadcasting Exercise-4 with Solution
Write a NumPy program that adds a scalar value to a 2D array of shape (5, 5) using broadcasting.
Sample Solution:
Python Code:
# Import the NumPy library
import numpy as np
# Create a 2D array with shape (5, 5)
array_2d = 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]])
# Define a scalar value
scalar = 10
# Add the scalar value to the 2D array using broadcasting
result = array_2d + scalar
# Print the original array and the result
print("Original 2D Array:\n", array_2d)
print("Scalar value:", scalar)
print("Result of array_2d + scalar:\n", result)
Output:
Original 2D 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]] Scalar value: 10 Result of array_2d + scalar: [[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]]
Explanation:
- Import the NumPy library: This step imports the NumPy library, which is essential for numerical operations.
- Create a 2D array with shape (5, 5): We use np.array to create a 2D array array_2d with shape (5, 5) and the given elements.
- Define a scalar value: We define a scalar value scalar to be added to the 2D array.
- Add the scalar value to the 2D array using broadcasting: NumPy automatically applies the scalar addition to each element of the 2D array using broadcasting.
- Print the original array and the result: This step prints the original 2D array array_2d, the scalar value, and the result of the addition.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Multiply 3D array by 1D array using NumPy Broadcasting.
Next: Element-wise multiplication with reshaped arrays using NumPy.
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/add-scalar-to-2d-array-using-numpy-broadcasting.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics