Mathematical Operations
NumPy makes it easy to perform mathematical operations on entire arrays. Instead of processing each value one by one, you can perform calculations on many values at the same time.
NumPy lets you perform mathematical calculations on entire arrays.
You can add, subtract, multiply, divide, find averages, calculate minimum and maximum values, and perform many other mathematical operations without writing loops for every element.
Basic Mathematical Operations
Let's start with a simple NumPy array:
import numpy as np numbers = np.array([10, 20, 30, 40]) print(numbers)
NumPy allows you to perform calculations directly on the entire array.
print(numbers + 5) print(numbers - 5) print(numbers * 5) print(numbers / 5)
[15 25 35 45] [ 5 15 25 35] [ 50 100 150 200] [2. 4. 6. 8.]
NumPy automatically applies the operation to every element.
Addition
You can add a number to every element in an array.
prices = np.array([100, 200, 300]) result = prices + 50 print(result)
[150 250 350]
NumPy performs:
100 + 50 = 150 200 + 50 = 250 300 + 50 = 350
You do not need a for loop for this.
Subtraction
Subtraction works in the same way.
prices = np.array([100, 200, 300]) result = prices - 20 print(result)
[ 80 180 280]
The value 20 is subtracted from every
element.
Multiplication
Multiplication can also be performed on the entire array.
numbers = np.array([2, 4, 6, 8]) result = numbers * 3 print(result)
[ 6 12 18 24]
Each value is multiplied by 3.
Division
Division works the same way.
numbers = np.array([10, 20, 30, 40]) result = numbers / 10 print(result)
[1. 2. 3. 4.]
Notice that NumPy returns floating-point values such as
1.0, 2.0, and so on.
Operations Between Two Arrays
Mathematical operations can also be performed between two arrays of compatible shapes.
a = np.array([10, 20, 30]) b = np.array([1, 2, 3]) result = a + b print(result)
[11 22 33]
NumPy performs the operation element by element:
10 + 1 = 11 20 + 2 = 22 30 + 3 = 33
Multiplying Two Arrays
prices = np.array([100, 200, 300]) quantity = np.array([2, 3, 4]) total = prices * quantity print(total)
[ 200 600 1200]
Each price is multiplied by its corresponding quantity.
100 × 2 = 200 200 × 3 = 600 300 × 4 = 1200
This type of element-by-element calculation is very common when working with numerical data.
Sum of an Array
The sum() function adds all values in an
array.
numbers = np.array([10, 20, 30, 40]) total = np.sum(numbers) print(total)
100
NumPy calculates:
10 + 20 + 30 + 40 = 100
Mean
The mean is the average of the values.
scores = np.array([70, 80, 90, 100]) average = np.mean(scores) print(average)
85.0
The calculation is:
(70 + 80 + 90 + 100) / 4 = 85
Mean is especially useful when analyzing datasets and model metrics.
Minimum and Maximum
You can find the smallest value using
np.min().
numbers = np.array([15, 8, 42, 23, 10]) print(np.min(numbers))
8
The largest value can be found using
np.max().
print(np.max(numbers))
42
Standard Deviation
Standard deviation tells us how spread out values are from the average.
scores = np.array([70, 75, 80, 85, 90]) std = np.std(scores) print(std)
7.0710678118654755
A smaller standard deviation generally means the values are closer together, while a larger value means they are more spread out.
This becomes useful in statistics and Machine Learning when understanding the distribution of data.
Absolute Value
The absolute value removes the negative sign from a number.
numbers = np.array([-10, -5, 0, 5, 10]) result = np.abs(numbers) print(result)
[10 5 0 5 10]
For example:
-10 → 10 -5 → 5 0 → 0 5 → 5 10 → 10
Power
The np.power() function raises values to a
specified power.
numbers = np.array([2, 3, 4]) result = np.power(numbers, 2) print(result)
[ 4 9 16]
This means:
2² = 4 3² = 9 4² = 16
Square Root
NumPy provides np.sqrt() for calculating
square roots.
numbers = np.array([4, 9, 16, 25]) result = np.sqrt(numbers) print(result)
[2. 3. 4. 5.]
Rounding Numbers
You can round decimal values using
np.round().
numbers = np.array([
1.234,
5.678,
9.876
])
result = np.round(numbers, 2)
print(result)
[1.23 5.68 9.88]
The second argument, 2, means that we want
two decimal places.
Mathematical Functions
NumPy also provides many mathematical functions such as sine, cosine, logarithms, and exponentials.
For example, you can calculate the exponential of values:
numbers = np.array([1, 2, 3]) result = np.exp(numbers) print(result)
NumPy can therefore handle much more than simple addition and subtraction.
Mathematical Operations on 2D Arrays
Mathematical operations become especially useful when working with two-dimensional datasets.
data = np.array([
[10, 20, 30],
[40, 50, 60]
])
print(np.sum(data))
210
NumPy adds every value in the entire array.
You can also calculate values row by row using
axis=1.
print(np.sum(data, axis=1))
[ 60 150]
The first row is 10 + 20 + 30 = 60, and the
second row is 40 + 50 + 60 = 150.
Operations by Column
With axis=0, NumPy performs the operation
down the rows, which gives a result for each column.
data = np.array([
[10, 20, 30],
[40, 50, 60]
])
print(np.sum(data, axis=0))
[50 70 90]
NumPy calculates:
10 + 40 = 50 20 + 50 = 70 30 + 60 = 90
Mathematical Operations in AI
Mathematical operations are everywhere in AI and Machine Learning.
For example, imagine model prediction errors:
errors = np.array([
2.5,
-1.5,
3.0,
-2.0,
1.0
])
We can calculate the average error:
average_error = np.mean(errors) print(average_error)
0.6
We can also remove negative signs when we only care about the size of the error:
absolute_errors = np.abs(errors) print(absolute_errors)
[2.5 1.5 3. 2. 1. ]
This kind of numerical processing is fundamental when evaluating and preparing data for AI models.
Example: Finding the Average and Scaling Data
Suppose we have some values:
data = np.array([10, 20, 30, 40, 50]) mean = np.mean(data) print(mean)
30.0
We can then subtract the mean from every value:
centered = data - mean print(centered)
[-20. -10. 0. 10. 20.]
This is a simple example of transforming data around its mean. Similar mathematical transformations are commonly used when preparing data for Machine Learning.
NumPy Mathematical Functions
| Function | Purpose | Example |
|---|---|---|
np.sum() |
Add values | np.sum(data) |
np.mean() |
Calculate average | np.mean(data) |
np.min() |
Find smallest value | np.min(data) |
np.max() |
Find largest value | np.max(data) |
np.std() |
Calculate standard deviation | np.std(data) |
np.abs() |
Calculate absolute values | np.abs(data) |
np.sqrt() |
Calculate square roots | np.sqrt(data) |
np.power() |
Raise values to a power | np.power(data, 2) |
np.round() |
Round decimal values | np.round(data, 2) |
Complete Example
Here is a small example that combines several NumPy mathematical operations:
import numpy as np
scores = np.array([70, 80, 90, 100])
total = np.sum(scores)
average = np.mean(scores)
minimum = np.min(scores)
maximum = np.max(scores)
print("Total:", total)
print("Average:", average)
print("Minimum:", minimum)
print("Maximum:", maximum)
Total: 340 Average: 85.0 Minimum: 70 Maximum: 100
This is much simpler than manually calculating each value with Python loops.
NumPy turns mathematical calculations into simple array operations.
You can perform arithmetic directly on arrays and use
functions such as sum(),
mean(), min(),
max(), std(),
sqrt(), and abs().
These operations are important because AI and Machine
Learning work heavily with numerical data. Once you
understand array operations, you can manipulate large
datasets much more efficiently than processing values
one at a time.