0
0
NumPydata~5 mins

Scalar operations on arrays in NumPy

Choose your learning style9 modes available
Introduction

Scalar operations let you add, subtract, multiply, or divide every number in an array by a single number easily. This helps you change all values quickly without writing loops.

You want to increase all prices in a list by 10%.
You need to convert temperatures from Celsius to Fahrenheit for many values.
You want to reduce all exam scores by 5 points.
You want to double the size measurements in a dataset.
You want to normalize data by dividing all values by the maximum value.
Syntax
NumPy
import numpy as np

array = np.array([values])

# Add a scalar
result = array + scalar

# Subtract a scalar
result = array - scalar

# Multiply by a scalar
result = array * scalar

# Divide by a scalar
result = array / scalar

Scalar means a single number, not a list or array.

Operations apply to every element in the array automatically.

Examples
Add 5 to each element: [6, 7, 8]
NumPy
import numpy as np

array = np.array([1, 2, 3])
result = array + 5
print(result)
Empty array multiplied by 10 stays empty: []
NumPy
import numpy as np

array = np.array([])
result = array * 10
print(result)
Single element array subtract 3: [7]
NumPy
import numpy as np

array = np.array([10])
result = array - 3
print(result)
Divide each element by 2: [1.0, 2.0, 3.0]
NumPy
import numpy as np

array = np.array([2, 4, 6])
result = array / 2
print(result)
Sample Program

This program shows how to add, multiply, and divide all elements in a numpy array by a scalar number. It prints the array before and after each operation.

NumPy
import numpy as np

# Create an array of exam scores
exam_scores = np.array([70, 85, 90, 60, 75])
print("Original exam scores:", exam_scores)

# Add 5 bonus points to all scores
bonus_points = 5
updated_scores = exam_scores + bonus_points
print("Scores after adding bonus points:", updated_scores)

# Multiply all scores by 1.1 to give a 10% increase
increased_scores = updated_scores * 1.1
print("Scores after 10% increase:", increased_scores)

# Divide all scores by 2 to find half scores
half_scores = increased_scores / 2
print("Half of the increased scores:", half_scores)
OutputSuccess
Important Notes

Time complexity is O(n) where n is the number of elements, because each element is processed once.

Space complexity is O(n) for the new array created by the operation.

Common mistake: Trying to add a list or array instead of a scalar causes element-wise addition, not scalar operation.

Use scalar operations when you want to apply the same change to every element quickly without loops.

Summary

Scalar operations apply a single number operation to every element in an array.

They are simple and fast ways to change all values at once.

Remember: the scalar is a single number, not a list or array.