Adding constants to numpy array?
To add a constant value to each element in a NumPy array, you can simply use the addition operator (+) with the constant value. NumPy will automatically broadcast the addition operation across all elements of the array. Here's how you can do it:
import numpy as np # Create a NumPy array arr = np.array([1, 2, 3, 4, 5]) # Define the constant value constant = 10 # Add the constant value to each element of the array result = arr + constant print("Original array:", arr) print("Constant added to array:", result)
This will output:
Original array: [1 2 3 4 5]
Constant added to array: [11 12 13 14 15]
As you can see, the constant value (10) has been added to each element of the original array. This approach works for NumPy arrays of any shape and dimensionality.
Comments
Post a Comment