Sub topic 4
How missing values behave in calculations
This chapter assumes you can create a Series and DataFrame, and that you know np.nan is a floating-point "not a number" value. Earlier chapters showed how to detect missing values. Here you will learn what they do to arithmetic, comparisons and aggregations. Most surprises come from one split: aggregations skip missing values, and element-wise operations pass them along.
Two rules to remember
- Aggregations skip missing values by default. Methods such as
sum,mean,min,maxandcounthave askipna=Truedefault. They ignore missing entries and compute on what is left. - Element-wise operations propagate missing values. If one input to
+,-,*or/is missing, the result at that position is missing.
Aggregations
import numpy as np
import pandas as pd
s = pd.Series([1.0, np.nan, 3.0])
print(s.sum()) # 4.0
print(s.mean()) # 2.0
print(s.count()) # 2, counts only non-missing values
print(len(s)) # 3, counts every row
print(s.sum(skipna=False)) # nanmean divides by 2, not 3. The missing row is left out of both the total and the count. If you expected a mean of 4/3, this is the cause. skipna=False is useful when a missing value should make the result visibly unreliable instead of being quietly ignored.
Aggregating nothing
A column that is entirely missing has nothing to sum, so sum returns 0.0 instead of NaN. Use min_count to change that.
import numpy as np
import pandas as pd
empty = pd.Series([np.nan, np.nan])
print(empty.sum()) # 0.0
print(empty.sum(min_count=1)) # nan
print(empty.mean()) # nanmin_count=1 means "return NaN unless at least one real value exists". Without it, a report could show a total of 0 for a group that has no data at all.
Arithmetic
import numpy as np
import pandas as pd
df = pd.DataFrame({
"a": [1.0, 2.0, np.nan, np.nan],
"b": [10.0, np.nan, 30.0, np.nan],
})
print(df["a"] + df["b"]) # 11.0, NaN, NaN, NaN
print(df["a"].add(df["b"], fill_value=0)) # 11.0, 2.0, 30.0, NaNThe + operator returns NaN wherever either side is missing. The method form add accepts fill_value, which substitutes a value for a missing entry on one side only. When both sides are missing the result stays NaN. The same option exists on sub, mul and div.
Comparisons
Comparisons with NaN never succeed, and that includes comparing NaN to itself.
import numpy as np
import pandas as pd
s = pd.Series([1.0, np.nan, 3.0])
print(s == np.nan) # False, False, False
print(s != np.nan) # True, True, True
print(s > 2) # False, False, True
print(s.isna()) # False, True, Falses == np.nan does not find the missing row, because no value equals NaN. The result is also the same for < and >, so a filter such as df[df["age"] <= 30] quietly drops rows with a missing age. To select them, use isna() or notna().
The pd.NA difference
pd.NA is the marker used by nullable dtypes, covered in a later chapter. It propagates more strictly than NaN: even comparisons return <NA> instead of False. Using it directly in an if statement raises a TypeError, because its truth value is unknown.
| Operation | With `np.nan` | With `pd.NA` |
|---|---|---|
| `x + 1` | `nan` | `<NA>` |
| `x == 1` | `False` | `<NA>` |
| `bool(x)` | `True` | raises `TypeError` |
Summary
Check count() against len() before trusting an aggregate. Use skipna=False when missing data should be visible in the result. Use min_count when an empty group should not produce 0. Use isna() for selecting missing rows, never ==.
Exercise
A Series is pd.Series([4.0, np.nan, 8.0, np.nan]). What do s.mean() and s.sum(skipna=False) return, and why do they differ in how they treat the missing values?
Show answer
s.mean() returns 6.0, because the two NaN values are skipped and the mean is (4 + 8) / 2. s.sum(skipna=False) returns nan, because with skipping turned off any missing value makes the total missing.
Exercise
You have a column price with some NaN values. Why does df[df["price"] != np.nan] fail to remove the missing rows, and what should you write instead?
Show answer
No value is ever equal to NaN, so != is True for every row, including the missing ones, and nothing is removed. Use df[df["price"].notna()].