Sub topic 4
How missing values behave in calculations
This chapter assumes you can create and index a Series and DataFrame, and that you know np.nan is NumPy's "not a number" value. It also assumes you have met isna for finding missing values. Here you learn what happens when missing values enter arithmetic, comparisons and aggregations. These rules explain many surprising results, such as a filter that silently drops rows or a sum that ignores data.
The core rule: missing in, missing out
A missing value means "unknown". Arithmetic on an unknown number gives an unknown result, so NaN propagates through operations.
import numpy as np
import pandas as pd
s = pd.Series([1.0, np.nan, 3.0])
print(s + 10) # 11.0, NaN, 13.0
print(s * s) # 1.0, NaN, 9.0
print(-s) # -1.0, NaN, -3.0The same holds across columns. If either operand in a row is missing, the result for that row is missing.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"price": [10.0, np.nan, 30.0],
"qty": [2.0, 5.0, np.nan],
})
df["total"] = df["price"] * df["qty"]
print(df)Only the first row has a total. The other two rows each have one missing operand.
There is one exception, which comes from the IEEE 754 floating-point standard that NumPy follows. Some operations have a defined answer whatever the unknown value is.
import numpy as np
print(np.nan ** 0) # 1.0
print(1 ** np.nan) # 1.0Any number to the power 0 is 1, and 1 to any power is 1. You will rarely hit this, but it shows that propagation is a rule of the number format, not something pandas adds.
Alignment creates missing values too
Arithmetic between two Series matches rows by index label. A label that exists in only one operand has no partner, so the result there is NaN.
import pandas as pd
a = pd.Series([1.0, 2.0], index=["x", "y"])
b = pd.Series([10.0, 20.0], index=["y", "z"])
print(a + b) # x NaN, y 12.0, z NaN
print(a.add(b, fill_value=0)) # x 1.0, y 12.0, z 20.0The method forms (add, sub, mul, div) accept fill_value. It stands in for a value that is missing on one side only. If both sides are missing at a label, the result stays NaN. Use fill_value only when a missing entry really means zero, such as "no sales that day". Otherwise you invent data.
Comparisons never match missing values
NaN is not equal to anything, including itself. Every comparison with it returns False, except !=, which returns True.
import numpy as np
import pandas as pd
age = pd.Series([25.0, np.nan, 31.0])
print(age == np.nan) # False, False, False
print(age != age) # False, True, False
print(age > 30) # False, False, True
print(age <= 30) # True, False, FalseTwo consequences follow.
- To find missing values, use
isna()ornotna(). Writingage == np.nannever finds anything. The expressionage != agedoes flag missing values, but it is cryptic, so avoid it. - A condition and its opposite are not complements. The row with the missing age is excluded from both
age > 30andage <= 30.
The second point causes quiet bugs in row counts.
import numpy as np
import pandas as pd
age = pd.Series([25.0, np.nan, 31.0])
older = (age > 30).sum()
not_older = (age <= 30).sum()
print(older + not_older) # 2, not 3
print((~(age > 30)).sum()) # 2: the negation includes the missing rowIf you want "everyone who is not over 30, including unknown ages", write that explicitly with ~(age > 30) or (age <= 30) | age.isna(). Decide on purpose whether unknown rows belong in each group.
Aggregations skip missing values by default
Aggregation methods such as sum, mean, min, max, std, median and prod have a skipna parameter that defaults to True. They drop the missing values and compute on what remains.
import numpy as np
import pandas as pd
s = pd.Series([2.0, np.nan, 4.0])
print(s.sum()) # 6.0
print(s.mean()) # 3.0, divided by 2 not 3
print(s.mean(skipna=False)) # nan
print(s.count()) # 2
print(len(s)) # 3
print(s.to_numpy().sum()) # nanNote these details.
meandivides by the number of non-missing values, not by the row count. The mean of[2, NaN, 4]is 3, not 2.count()counts non-missing values.len(s)ands.sizecount all rows. Comparing them is a quick check for how much data a statistic rests on.- A plain NumPy array does not skip.
s.to_numpy().sum()returnsnan. Moving between pandas and NumPy can change the result without any error. - Set
skipna=Falsewhen a missing value should invalidate the whole result, for example a total that must be complete to be reportable.
Empty results: sum, product and min_count
When every value is missing, the skipped set is empty. Each aggregation then returns its identity value, if it has one.
import numpy as np
import pandas as pd
empty = pd.Series([np.nan, np.nan])
print(empty.sum()) # 0.0
print(empty.prod()) # 1.0
print(empty.mean()) # nan
print(empty.sum(min_count=1)) # nanAn all-missing group has a sum of 0.0, which looks like real data. The min_count parameter sets the minimum number of non-missing values needed to produce a result. Otherwise you get NaN. With min_count=1, a sum over no data is reported as unknown, not zero.
Aggregating across columns
On a DataFrame, axis=1 aggregates across each row. Skipping applies there too.
import numpy as np
import pandas as pd
df = pd.DataFrame({"a": [1.0, np.nan], "b": [2.0, np.nan]})
print(df.sum(axis=1)) # 3.0, 0.0
print(df.mean(axis=1)) # 1.5, NaNThe second row is entirely missing. Its sum is 0.0 but its mean is NaN, the same split as above.
Other operations that skip or keep
| Operation | Behaviour with missing values |
|---|---|
| `cumsum()`, `cumprod()` | Skip the missing value in the running total, but leave `NaN` at that position |
| `corr()`, `cov()` | Use only the pairs where both values are present |
| `value_counts()` | Drops missing values unless `dropna=False` |
| `nunique()` | Ignores missing values unless `dropna=False` |
| `unique()`, `drop_duplicates()` | Treat all `NaN` as equal to each other, so one `NaN` is kept |
| `sort_values()` | Places missing values last by default (`na_position="last"`) |
Note that unique() and drop_duplicates() treat NaN as equal to NaN, even though == says they differ. Operations that group or deduplicate values use their own rule for missing keys.
The decision flow
The diagram summarises how pandas treats a missing value in each kind of operation.
Nullable types: three-valued logic
Columns with the nullable dtypes (Int64, boolean, string) use pd.NA instead of NaN. pd.NA still propagates in arithmetic. In comparisons it does not turn into False. The comparison result is itself missing.
import pandas as pd
n = pd.Series([1, None, 3], dtype="Int64")
print(n + 1) # 2, <NA>, 4
print(n > 1) # False, <NA>, True (dtype boolean)
print(n == pd.NA) # <NA>, <NA>, <NA>
print(n.sum()) # 4This follows the idea that "unknown compared with 1" is unknown, which is more honest than False. It also means the complement problem from earlier changes. ~(n > 1) is True, <NA>, False, so the unknown stays unknown.
Logical operators on the boolean dtype use Kleene logic. A result is known whenever the known operand settles it.
import pandas as pd
flags = pd.array([True, False, None], dtype="boolean")
print(flags | True) # True, True, True
print(flags & False) # False, False, False
print(flags & True) # True, False, <NA>True | unknown is True because the answer does not depend on the unknown. False & unknown is False for the same reason. In other cases the result stays <NA>.
A single pd.NA cannot be used as a condition, because pandas will not guess its truth value.
import pandas as pd
try:
if pd.NA:
print("yes")
except TypeError as err:
print(type(err).__name__, err)This prints TypeError boolean value of NA is ambiguous. The error is intended. It stops you from branching on an unknown. Test with pd.isna(value) first.
When you filter with a boolean mask that contains <NA>, pandas treats <NA> as False and drops that row. The row is excluded without any warning, as with float NaN.
Summary of the rules
- Arithmetic with a missing value gives a missing value. Aligning two Series on different labels creates new missing values.
- Comparisons with float
NaNreturnFalse(orTruefor!=). Useisna()to detect missing values. - With nullable dtypes, comparisons return
<NA>, and logical operators follow three-valued logic. - Pandas aggregations skip missing values by default. NumPy array reductions do not.
- An all-missing sum is
0.0and an all-missing product is1.0, unless you setmin_count.
Exercise
A Series is pd.Series([4.0, np.nan, 6.0, np.nan]). (a) What do s.mean() and s.mean(skipna=False) return? (b) What do (s > 5).sum() and (s <= 5).sum() return, and why do they not add up to len(s)? (c) How would you make a sum over an all-missing group return NaN instead of 0.0?
Show answer
(a) s.mean() returns 5.0, because the mean is computed over the two non-missing values (4 and 6). s.mean(skipna=False) returns nan. (b) (s > 5).sum() is 1 (only 6.0) and (s <= 5).sum() is 1 (only 4.0). The two total 2, while len(s) is 4, because comparisons with NaN are False in both conditions, so the two missing rows match neither. (c) Pass min_count=1, for example s.sum(min_count=1), so a result needs at least one non-missing value.