NumPy has fast mathematical functions that work on whole arrays: arithmetic, powers, logs, trigonometry, rounding and statistics. You can also choose to apply them along rows or columns.
Prerequisites
Element-wise Arithmetic
import numpy as np
a = np.array([10, 20, 30])
b = np.array([1, 2, 3])
print(a + b, a - b, a * b, a / b)
print(np.add(a, b), a ** 2, a % 7)
[11 22 33] [ 9 18 27] [10 40 90] [10. 10. 10.] [11 22 33] [100 400 900] [3 6 2]
Universal Functions (ufuncs)
x = np.array([1, 4, 9])
print(np.sqrt(x))
print(np.exp([0, 1]))
print(np.log([1, np.e]))
print(np.round(np.sin(np.pi / 2), 2))
[1. 2. 3.] [1. 2.71828183] [0. 1.] 1.0
Rounding
v = np.array([1.25, 2.5, -1.7])
print(np.round(v, 1), np.floor(v), np.ceil(v), np.trunc(v))
Explanation: np.round uses round-half-to-even, which is why 1.25 becomes 1.2.
[ 1.2 2.5 -1.7] [ 1. 2. -2.] [ 2. 3. -1.] [ 1. 2. -1.]
Statistics and the axis Parameter
m = np.array([[1, 2, 3],
[4, 5, 6]])
print(m.sum(), m.mean())
print(m.sum(axis=0)) # down the columns
print(m.sum(axis=1)) # across the rows
print(m.max(axis=1), m.argmax(axis=1))
Explanation: axis=0 collapses the rows (one result per column). axis=1 collapses the columns (one result per row). argmax gives the position of the largest value.
21 3.5 [5 7 9] [ 6 15] [3 6] [2 2]
Cumulative Functions
print(np.cumsum([1, 2, 3, 4]))
print(np.diff([1, 4, 9, 16]))
[ 1 3 6 10] [3 5 7]
Broadcasting
m = np.array([[1, 2, 3],
[4, 5, 6]])
print(m + np.array([10, 20, 30]))
print(m * 2)
Explanation: NumPy “stretches” the smaller array across the larger one when the shapes are compatible. This is called broadcasting.
[[11 22 33] [14 25 36]] [[ 2 4 6] [ 8 10 12]]
Matrix Multiplication
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print(A * B) # element-wise
print(A @ B) # matrix product
[[ 5 12] [21 32]] [[19 22] [43 50]]
Common Errors
| Problem | Cause and fix |
|---|---|
ValueError: operands could not be broadcast together |
Shapes are not compatible. Check .shape and reshape if needed. |
RuntimeWarning: divide by zero |
A zero in the divisor gives inf. Filter or use np.divide with where=. |
Practice Exercises
- Normalise an array to the range 0–1 using min and max.
- Find the column-wise average of a 3×4 array.
Interview Questions
Q: What does axis=0 mean?
Operate down the rows, giving one result per column.
Q: * vs @?
* is element-wise; @ is matrix multiplication.
Summary
NumPy ufuncs apply maths to whole arrays; use axis to work by row or column, broadcasting to combine shapes, and @ for matrix products.
Next: Slicing and Indexing · Sorting
Machine Learning Tutorials, Courses and Certifications