When you apply an arithmetical operation or a function to a Numpy array, it gets applied to every element in the array.
import numpy as np
values = np.array([1, 2, 3])
print(values) # Original values
print(values * 2) # Multiply values by 2
print(values ** 2) # Square the values
print(np.sin(values)) # sin() of each value
[1 2 3]
[2 4 6]
[1 4 9]
[0.84147098 0.90929743 0.14112001]
For example, values * 2 returns a new Numpy array that’s the same as the first one, except all values are multiplied by two.
If you want to modify the original array, assign the result back to the original variable or use operators like *=, +=, etc.
import numpy as np
values = np.array([1, 2, 3])
values *= 2
print(values)
[2 4 6]
Leave a Reply