w3resource

Add Scalar to 2D array using NumPy Broadcasting


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: