w3resource

Add Scalar to 2D array using NumPy Broadcasting


4. Scalar Addition to a 2D Array

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.

For more Practice: Solve these Related Problems:

  • Add a scalar to a 2D array and then compute the mean of the new array to verify the operation.
  • Create a function that adds a constant value to each element of a 2D array and then normalizes the result.
  • Implement a solution that adds a scalar and then subtracts the original array from the result to produce an array of constant differences.
  • Test the scalar addition on arrays of varying sizes and data types to ensure broadcasting works consistently.

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.



Follow us on Facebook and Twitter for latest update.