Sub topic 8
Mean, median, and standard deviation along an axis
This chapter assumes you know basic Python syntax, can create arrays with np.array and np.arange, and understand what an array's shape means. It also assumes you have met sum with the axis argument. Here the same rule is applied to statistics: mean, median, std, and var.
The axis rule carries over
Statistical functions are reductions, like sum. The axis argument works the same way. The axis you name is the one that disappears from the result's shape.
axis=0runs down the rows, so each column gives one value.axis=1runs across the columns, so each row gives one value.- No axis reduces the whole array to a single number.
Take a small table of test scores. Each row is a student and each column is a test.
import numpy as np
scores = np.array([[70, 80, 90],
[60, 85, 95],
[80, 75, 100],
[90, 90, 70]])
print(scores.shape) # (4, 3)
print(scores.mean()) # 82.91666666666667
print(scores.mean(axis=0)) # [75. 82.5 88.75]
print(scores.mean(axis=1)) # [80. 80. 85. 83.33333333]scores.mean(axis=0) has shape (3,): one average per test. scores.mean(axis=1) has shape (4,): one average per student.
Mean
The mean is the sum divided by the count. Along an axis, the count is the length of that axis. For scores, axis=0 divides each column total by 4, and axis=1 divides each row total by 3.
The result of mean is always a floating-point number, even for integer input. For integer arrays NumPy computes the mean using float64, so you do not need to convert the array first.
You can call it as a method (scores.mean(axis=0)) or as a function (np.mean(scores, axis=0)). Both give the same result.
Median
The median is the middle value after sorting. For an even count, it is the average of the two middle values. Use it when a few extreme values would distort the mean.
median is not an array method. Call np.median.
import numpy as np
scores = np.array([[70, 80, 90],
[60, 85, 95],
[80, 75, 100],
[90, 90, 70]])
print(np.median(scores, axis=0)) # [75. 82.5 92.5]
print(np.median(scores, axis=1)) # [80. 85. 80. 90.]Look at the first column: 70, 60, 80, 90. Sorted, that is 60, 70, 80, 90. The two middle values are 70 and 80, so the median is 75. For the first row, 70, 80, 90, the middle value is 80.
Median and mean can differ a lot when the data has an outlier, which is a value far from the rest.
import numpy as np
times = np.array([[1.0, 2.0],
[1.2, 2.1],
[50.0, 2.2]])
print(times.mean(axis=0)) # [17.4 2.1]
print(np.median(times, axis=0)) # [1.2 2.1]The 50.0 pulls the first column's mean up to 17.4, while the median stays at 1.2.
Standard deviation and variance
The variance measures how far values spread from their mean. It is the average of the squared distances from the mean. The standard deviation is the square root of the variance, so it has the same units as the data.
import numpy as np
scores = np.array([[70, 80, 90],
[60, 85, 95],
[80, 75, 100],
[90, 90, 70]])
print(scores.std(axis=0)) # spread of each test across students
print(scores.var(axis=0)) # the same spread, squared
print(scores.std(axis=1)) # spread of each student's scores across testsBoth functions accept axis, and the result shape follows the same rule as for mean.
The ddof argument
By default NumPy divides by N, the number of values along the axis. This is the population standard deviation. When your data is a sample of a larger group, statisticians divide by N - 1 instead. Set ddof=1 ("delta degrees of freedom") to get that.
import numpy as np
x = np.array([2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0])
print(x.std()) # 2.0
print(x.std(ddof=1)) # 2.138089935299395Pandas uses ddof=1 by default, and NumPy uses ddof=0. This difference is a common reason for results that disagree between the two libraries.
Combining statistics with keepdims
A frequent task is to standardize data. This means subtracting the mean and dividing by the standard deviation, so each column has mean 0 and standard deviation 1. This is called a z-score.
For column-wise standardization, the reduced results have shape (3,), which broadcasts against (4, 3) without help.
import numpy as np
scores = np.array([[70, 80, 90],
[60, 85, 95],
[80, 75, 100],
[90, 90, 70]], dtype=float)
z = (scores - scores.mean(axis=0)) / scores.std(axis=0)
print(z.mean(axis=0).round(10)) # [0. 0. 0.]
print(z.std(axis=0)) # [1. 1. 1.]For row-wise standardization the reduced results have shape (4,). That does not broadcast against (4, 3), because NumPy lines up shapes from the right and compares 3 with 4. Use keepdims=True so the result has shape (4, 1).
import numpy as np
scores = np.array([[70, 80, 90],
[60, 85, 95],
[80, 75, 100],
[90, 90, 70]], dtype=float)
mu = scores.mean(axis=1, keepdims=True)
sigma = scores.std(axis=1, keepdims=True)
print(mu.shape) # (4, 1)
z_rows = (scores - mu) / sigma
print(z_rows.mean(axis=1).round(10)) # [0. 0. 0. 0.]keepdims works for mean, std, var, and np.median.
Edge cases
Constant data
If every value along the axis is the same, the standard deviation is 0. Dividing by it gives nan (for 0/0) and a RuntimeWarning. Check for zero before dividing.
import numpy as np
a = np.array([[1.0, 5.0],
[1.0, 7.0],
[1.0, 9.0]])
sigma = a.std(axis=0)
print(sigma) # [0. 1.63299316]
safe = np.where(sigma == 0, 1.0, sigma)
z = (a - a.mean(axis=0)) / safe
print(z[:, 0]) # [0. 0. 0.]Empty axes
The mean of an empty selection has no meaning. NumPy returns nan and emits a warning.
import numpy as np
empty = np.empty((0, 3))
print(empty.mean(axis=0)) # [nan nan nan], with a RuntimeWarningMissing values
If any value along the axis is nan, then mean, median, std, and var return nan for that slice. Use np.nanmean, np.nanmedian, np.nanstd, and np.nanvar to skip those values.
import numpy as np
c = np.array([[1.0, np.nan],
[3.0, 4.0]])
print(c.mean(axis=0)) # [2. nan]
print(np.nanmean(c, axis=0)) # [2. 4.]
print(np.nanstd(c, axis=1)) # [0. 0.5]The count used for the mean is the number of non-NaN values, so the result is not the same as filling the gaps with zero.
Precision
For float32 input, mean accumulates in float32 by default, which can lose precision over many values. Pass dtype=np.float64 to accumulate in higher precision.
import numpy as np
big = np.full((1_000_000, 2), 0.1, dtype=np.float32)
print(big.mean(axis=0, dtype=np.float64))Choosing between them
| Function | Measures | Sensitive to outliers | Method form |
|---|---|---|---|
| `mean` | Average | Yes | `a.mean(axis=...)` |
| `np.median` | Middle value | No | None, use `np.median` |
| `std` | Spread, same units as data | Yes | `a.std(axis=...)` |
| `var` | Spread, squared units | Yes | `a.var(axis=...)` |
Common mistakes
- Reading
axis=0as "along the rows" and expecting one value per row. It gives one value per column. - Subtracting a row-wise mean without
keepdims=True. With a square array this runs without error but gives the wrong answer, because the(n,)result is broadcast across columns. - Calling
a.median(). There is no such method. Usenp.median(a). - Assuming
stduses the sample formula. It usesddof=0unless you say otherwise. - Forgetting that one
nanspoils the whole slice for the regular functions.
Exercises
Exercise
An array a has shape (5, 4). What are the shapes of a.mean(axis=0), np.median(a, axis=1), a.std(axis=1, keepdims=True), and a.var()?
Show answer
a.mean(axis=0) has shape (4,). np.median(a, axis=1) has shape (5,). a.std(axis=1, keepdims=True) has shape (5, 1). a.var() is a single number with shape ().
Exercise
Given a = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 9.0]]), write one line that subtracts each row's mean from that row, so every row has mean 0.
Show answer
a - a.mean(axis=1, keepdims=True). The keepdims=True gives the means shape (2, 1), which broadcasts across the three columns. Without it, the shape (2,) would not broadcast against (2, 3).
Exercise
For x = np.array([1.0, 2.0, 3.0, 4.0]), x.std() returns about 1.118. What argument makes NumPy return the sample standard deviation, and what is the approximate value?
Show answer
Pass ddof=1. The result is about 1.291, because the sum of squared deviations (5.0) is divided by 3 instead of 4 before taking the square root.