Sub topic 11
Aggregating data with missing values
This chapter assumes you can create NumPy arrays, read an array's shape, and use the axis argument with sum, mean, min, and max. It covers what happens when an array contains missing values, and how to aggregate along an axis anyway.
Why NaN breaks a normal aggregation
NumPy marks a missing float with np.nan, which stands for "not a number". NaN is contagious. Any ordinary aggregation that touches a NaN returns NaN for that result.
The axis argument limits the damage. Only the slices that contain a NaN become NaN, and the other slices are still computed normally.
import numpy as np
c = np.array([[1.0, np.nan],
[3.0, 4.0]])
print(c.sum()) # nan
print(c.sum(axis=0)) # [ 4. nan]
print(c.sum(axis=1)) # [nan 7.]With axis=0 the first column adds to 4.0, but the second column holds a NaN, so its total is NaN. With axis=1 the first row is NaN and the second row is 7.0.
Because NaN is a float value, an integer array cannot hold it. Arrays with missing values are always floating point.
The nan-prefixed functions
NumPy provides a NaN-aware version of most aggregations. These versions skip missing values and compute the result from the values that remain.
| Regular function | NaN-aware function |
|---|---|
| `np.sum` | `np.nansum` |
| `np.mean` | `np.nanmean` |
| `np.median` | `np.nanmedian` |
| `np.std` | `np.nanstd` |
| `np.max` | `np.nanmax` |
| `np.min` | `np.nanmin` |
| `np.argmax` | `np.nanargmax` |
| `np.cumsum` | `np.nancumsum` |
They accept the same axis and keepdims arguments as the regular functions, so the shape rules you already know still apply.
import numpy as np
c = np.array([[1.0, np.nan],
[3.0, 4.0]])
print(np.nansum(c, axis=0)) # [4. 4.]
print(np.nanmean(c, axis=1)) # [1. 3.5]In the second line, row 0 has only one valid value (1.0), so its mean is 1.0. Row 1 has two valid values, so its mean is (3.0 + 4.0) / 2 = 3.5. The mean divides by the count of valid values, not by the row length.
Edge cases to know
A slice that contains only NaN has no valid values to work with. The results differ by function:
np.nansumreturns0.0, because the sum of nothing is zero.np.nanmeanreturnsnanand emits aRuntimeWarningabout the mean of an empty slice.np.nanmaxandnp.nanminreturnnanand emit a warning.np.nanargmaxandnp.nanargminraise aValueError.
import numpy as np
d = np.array([[np.nan, np.nan],
[2.0, 6.0]])
print(np.nansum(d, axis=1)) # [0. 8.]
print(np.nanmean(d, axis=1)) # [nan 4.] (with a RuntimeWarning)Counting missing values
Before you aggregate, it often helps to see how much data is missing. np.isnan returns a Boolean array, and True counts as 1 when summed.
import numpy as np
c = np.array([[1.0, np.nan],
[3.0, 4.0]])
print(np.isnan(c).sum(axis=0)) # [0 1]
print(np.isnan(c).sum(axis=1)) # [1 0]This gives the number of missing values per column and per row.
Common mistakes
- Comparing with
==.np.nan == np.nanisFalse, soc == np.nannever finds anything. Usenp.isnan(c). - Silent skipping. A NaN-aware function hides missing data. If a row has one valid value out of a hundred, its mean still looks normal. Check the counts first.
- Mixing up the two families. Use
np.nansum, notnp.sum, if you want missing values skipped. The regular function never skips them.
Exercise
Given e = np.array([[2.0, np.nan, 4.0], [np.nan, np.nan, 6.0]]), what do np.nanmean(e, axis=1) and np.isnan(e).sum(axis=1) return?
Show answer
np.nanmean(e, axis=1) returns [3. 6.], because row 0 averages 2.0 and 4.0, and row 1 has only 6.0. np.isnan(e).sum(axis=1) returns [1 2], the count of missing values in each row.