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 of sum, mean, min, and max. It also assumes you know that keepdims=True leaves the reduced axis in the result with length 1. Here you will see what happens when some of the values are missing, and how to aggregate along an axis anyway.
How missing values are stored
NumPy has no special "missing" type for ordinary arrays. The usual convention is np.nan, short for "not a number". It is a floating-point value defined by the IEEE 754 standard. Three consequences follow:
- An array that holds
np.nanmust have a float dtype. Puttingnp.naninto an integer array raises an error, and building an array from a mix of ints andnp.nangives you floats. np.nan == np.nanisFalse. To find missing values, usenp.isnan(a), nota == np.nan.- Any arithmetic with
nanproducesnan. This is called propagation, and it is the cause of most surprises in this chapter.
import numpy as np
c = np.array([[1.0, np.nan],
[3.0, 4.0]])
print(c.dtype) # float64
print(c == np.nan) # [[False False]
# [False False]]
print(np.isnan(c)) # [[False True]
# [False False]]
print(np.isnan(c).sum()) # 1A boolean array counts as 0 and 1 when summed. That makes np.isnan(c).sum(axis=0) a quick way to count missing values per column.
NaN propagation in a reduction
A regular aggregation has no rule for skipping values. If any value in a slice is nan, the result for that slice is nan. The axis argument decides which slices are affected.
import numpy as np
c = np.array([[1.0, np.nan],
[3.0, 4.0]])
print(c.sum(axis=0)) # [ 4. nan]
print(c.sum(axis=1)) # [nan 7.]
print(c.sum()) # nan
print(c.max(axis=0)) # [ 3. nan]With axis=0, each result entry comes from one column. Only column 1 contains the nan, so only entry 1 is poisoned. With axis=1, each entry comes from one row, so row 0 is the poisoned one. With no axis, the whole array is one slice and the single result is nan.
The damage stays inside the slices that contain missing data. You can see that as soon as you pick the direction.
The nan-prefixed functions
NumPy provides a second family of functions that ignore nan while reducing. Each has the same axis and keepdims arguments as its regular counterpart.
| Regular function | NaN-aware function | Behavior |
|---|---|---|
| `np.sum` | `np.nansum` | Treats NaN as 0 |
| `np.mean` | `np.nanmean` | Divides by the count of non-NaN values |
| `np.median` | `np.nanmedian` | Median of the non-NaN values |
| `np.std`, `np.var` | `np.nanstd`, `np.nanvar` | Computed from non-NaN values only |
| `np.min`, `np.max` | `np.nanmin`, `np.nanmax` | Extremes of the non-NaN values |
| `np.argmin`, `np.argmax` | `np.nanargmin`, `np.nanargmax` | Index of the extreme non-NaN value |
| `np.cumsum`, `np.cumprod` | `np.nancumsum`, `np.nancumprod` | Treat NaN as 0 (sum) or 1 (product) |
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]
print(np.nanmax(c, axis=1)) # [1. 4.]
print(np.nanmean(c, axis=0)) # [2. 4.]Look at np.nanmean(c, axis=0). Column 1 holds nan and 4.0, and the mean is 4.0, not 2.0. The nan is removed from the slice and the count, so the divisor is 1. If you instead replaced nan with 0 and called mean, you would get 2.0. The two answers differ, so decide which one matches your data. Missing usually means "unknown", and nanmean is then the correct choice. Zero means "measured and found to be zero".
Index functions need their own variants
argmax does not follow the "skip it" idea. It treats nan as larger than every number, so it returns the position of the nan.
import numpy as np
c = np.array([[1.0, np.nan],
[3.0, 4.0]])
print(c.argmax(axis=1)) # [1 1]
print(np.nanargmax(c, axis=1)) # [0 1]
print(np.nanargmin(c, axis=0)) # [0 1]In row 0, plain argmax reports column 1, which is the nan. nanargmax reports column 0, the only real value. Because the plain version returns an index, no nan shows up in the output, and the mistake is silent. Use the nan variant whenever the data can contain missing values.
Slices that are entirely NaN
If every value in a slice is nan, there is nothing left to aggregate. The functions handle this case in different ways:
nansumreturns0.0, because the sum of nothing is 0.nanprodreturns1.0.nanmean,nanmedian,nanstd, andnanmaxreturnnanand emit aRuntimeWarning.nanargmaxandnanargminraiseValueError: All-NaN slice encountered.
import numpy as np
import warnings
d = np.array([[1.0, 2.0],
[np.nan, np.nan]])
print(np.nansum(d, axis=1)) # [3. 0.]
with warnings.catch_warnings():
warnings.simplefilter("ignore")
print(np.nanmean(d, axis=1)) # [1.5 nan]
try:
np.nanargmax(d, axis=1)
except ValueError as err:
print("ValueError:", err)Row 1 above shows the problem. nansum reports 0.0 for a row that has no data at all, and that is indistinguishable from a row that really sums to zero. If the difference matters, count the valid values first and check for zero.
import numpy as np
d = np.array([[1.0, 2.0],
[np.nan, np.nan]])
valid_counts = (~np.isnan(d)).sum(axis=1)
print(valid_counts) # [2 0]
totals = np.nansum(d, axis=1)
totals_or_nan = np.where(valid_counts > 0, totals, np.nan)
print(totals_or_nan) # [ 3. nan]Combining NaN-aware results with broadcasting
The keepdims=True argument works with the nan functions in the same way as with the regular ones. Centering each column on its own mean, ignoring missing values, looks like this:
import numpy as np
c = np.array([[1.0, np.nan],
[3.0, 4.0]])
col_means = np.nanmean(c, axis=0, keepdims=True)
print(col_means.shape) # (1, 2)
centered = c - col_means
print(centered)
# [[-1. nan]
# [ 1. 0.]]The missing entry stays missing, since nan minus anything is nan. Every other entry is centered using a mean that was not distorted by the gap. That is usually what you want: the mean ignores the gap, and the gap stays visible in the output.
The where argument
Reductions such as sum, mean, min, max, std, and var also accept a where argument, a boolean array that selects which elements take part. It lets you ignore any set of elements, not only nan. Typical uses are skipping a sentinel value or ignoring rows flagged as invalid.
import numpy as np
c = np.array([[1.0, np.nan],
[3.0, 4.0]])
mask = ~np.isnan(c)
print(c.sum(axis=0, where=mask)) # [4. 4.]
print(c.mean(axis=0, where=mask)) # [2. 4.]For min and max, an empty selection has no natural result, so NumPy requires an initial value when you use where. For example, c.max(axis=0, where=mask, initial=-np.inf). For plain nan handling, the nan functions are simpler and more readable.
Pitfalls
- Using a sentinel such as -999. Some data sets store missing values as a special number. NumPy does not know this, and
meanwill include the sentinel. Convert it first witha = np.where(a == -999, np.nan, a), after making sure the array is float. - Hiding the problem.
nansumandnanmeannever report that data were missing. Count missing values withnp.isnan(a).sum(axis=...)if the amount of missing data affects how far you can trust the result. - Mixing up the axis. A
nanthat appears in the result tells you which slice contained missing data. If you expected a column to be affected and see a row instead, check that you used the intended axis. - Warnings in a loop. The
RuntimeWarningfor all-NaN slices is shown once per location by default. Silence it only after you have decided how to treat those slices. - Using
==oriswith NaN. Usenp.isnan. For a combined check across several arrays,np.isfinitealso excludes infinities.
Exercise
Given c = np.array([[2.0, np.nan, 6.0], [np.nan, np.nan, 3.0]]), write expressions that give (a) the mean of each row, ignoring NaN, (b) the number of valid values in each column, and (c) the column index of the largest valid value in each row. What does each return, and what would np.nanmean(c, axis=0) do for column 1?
Show answer
(a) np.nanmean(c, axis=1) returns [4. 3.]. (b) (~np.isnan(c)).sum(axis=0) returns [1 0 2]. (c) np.nanargmax(c, axis=1) returns [2 2]. For column 1, every value is NaN, so np.nanmean(c, axis=0) returns nan for that column and emits a RuntimeWarning "Mean of empty slice". The other columns give 2.0 and 4.5.