Sub topic 13
Pitfalls to avoid
This chapter assumes you can detect missing values with isna, use dropna and fillna, and have seen nullable dtypes such as Int64. It collects the mistakes that leave code running without errors but producing wrong results. Each section gives the symptom, the cause, and the fix.
Comparing with NaN
NaN is not equal to anything, including itself. A comparison against np.nan therefore never matches, and != matches every row.
import numpy as np
import pandas as pd
s = pd.Series([1.0, np.nan, 3.0])
print((s == np.nan).tolist()) # [False, False, False]
print((s != np.nan).tolist()) # [True, True, True]
print(s.notna().tolist()) # [True, False, True]A filter such as df[df["age"] != np.nan] looks like it removes missing rows. It removes nothing. Use isna() and notna(), or dropna, to test for missing values.
Aggregations that hide missing data
Aggregations skip missing values by default. That is usually what you want, but two consequences surprise people.
- A mean is computed over fewer values than the row count suggests. A column that is 90% missing still gives a confident-looking average.
- The sum of an all-missing column is
0.0, notNaN.
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 tells sum to return NaN unless at least one real value exists. Without it, a group with no data is indistinguishable from a group whose total is zero. Compare df["col"].count() (non-missing values) with len(df) before you trust an aggregate.
Dropping too much with dropna
df.dropna() uses how="any" across all columns. One sparse, unimportant column can remove nearly every row.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"id": [1, 2, 3, 4],
"age": [25, 30, np.nan, 41],
"notes": [None, None, "vip", None],
})
print(len(df.dropna())) # 0
print(len(df.dropna(subset=["age"]))) # 3Name the columns that matter with subset. Print the row count before and after, so a drop from 10,000 rows to 12 is visible. Also check whether the dropped rows differ systematically from the kept ones. If they do, the remaining data is a biased sample (see the chapter on why data is missing).
Inplace and chained assignment
Calling fillna on a column selected from a DataFrame, with inplace=True, is unreliable:
# Do not do this
df["age"].fillna(0, inplace=True)The column selection may be a temporary object, so the original DataFrame may not change. pandas 2.x warns about this pattern. Under copy-on-write, the default in pandas 3.0, it never updates df. The inplace option rarely saves memory, because most methods build a new object internally anyway. Assign the result back:
import numpy as np
import pandas as pd
df = pd.DataFrame({"age": [25, np.nan, 31]})
df["age"] = df["age"].fillna(df["age"].median())
print(df)The same rule applies to df[df["x"] > 0]["y"] = 1. Use one .loc call instead: df.loc[df["x"] > 0, "y"] = 1.
Silent type changes
Plain NumPy-backed integer and boolean columns cannot hold a missing value. When one appears, pandas changes the dtype without warning.
import pandas as pd
ints = pd.Series([1, None, 3])
bools = pd.Series([True, None, False])
print(ints.dtype) # float64
print(bools.dtype) # object
filled = ints.fillna(0)
print(filled.dtype) # float64
print(filled.astype("int64").dtype) # int64Filling does not restore the old type. fillna(0) leaves a float column, and IDs such as 3.0 then break joins and exports. There are two safe routes:
- Fill first, then convert with
astype("int64"). This works only when no missing values remain. - Keep the missing values and use a nullable dtype from the start:
Int64,boolean,string.
import pandas as pd
ints = pd.Series([1, None, 3], dtype="Int64")
bools = pd.Series([True, None, False], dtype="boolean")
print(ints.dtype, bools.dtype) # Int64 booleanA boolean column of object dtype is especially risky. It holds Python True, False and None, so ~mask and & behave unexpectedly.
Truth tests with pd.NA
pd.NA means "unknown", so Python cannot turn it into True or False:
import pandas as pd
try:
if pd.NA:
pass
except TypeError as e:
print(e) # boolean value of NA is ambiguousThe same error appears when if row["flag"]: meets a missing value in a boolean column. Test explicitly with pd.isna(value) first, or call fillna(False) on the mask.
Groupby drops missing keys
groupby leaves out rows whose key is missing. Those rows vanish from every group total, and the totals no longer add up to the whole.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", None, "Oslo", "Rome"],
"age": [20.0, 30.0, np.nan, 40.0],
})
print(df.groupby("city").size()) # Oslo 2, Rome 1
print(df.groupby("city", dropna=False).size()) # also a NaN group of 1Pass dropna=False when the missing-key rows matter, or fill the key with a label such as "unknown" before grouping. A related trap appears in group-wise filling: if every value in a group is missing, the group mean is NaN, so fillna leaves those rows unchanged. After a transform("mean") fill, check df["score"].isna().sum() again.
Merge matches missing keys to each other
In SQL, NULL never equals NULL, so rows with missing join keys do not match. pandas merge does the opposite: missing keys on both sides match each other.
import numpy as np
import pandas as pd
left = pd.DataFrame({"key": [1.0, np.nan], "l": ["a", "b"]})
right = pd.DataFrame({"key": [np.nan, 2.0], "r": ["x", "y"]})
print(left.merge(right, on="key", how="inner"))The result contains one row: key is NaN, l is b, r is x. Two unrelated records have been paired because both were missing an identifier. Remove missing keys before the merge:
import numpy as np
import pandas as pd
left = pd.DataFrame({"key": [1.0, np.nan], "l": ["a", "b"]})
right = pd.DataFrame({"key": [np.nan, 2.0], "r": ["x", "y"]})
clean = left.dropna(subset=["key"]).merge(
right.dropna(subset=["key"]), on="key", how="inner"
)
print(len(clean)) # 0Also check the merge result for rows where a left join produced new missing values. Those come from unmatched keys, and they are not the same as missing values in the source data.
Filling with statistics leaks information
If you fill with a mean or median computed from the full dataset and then split into training and test sets, the test rows have influenced the training data. Compute the statistic from the training part only and reuse it for both parts.
import numpy as np
import pandas as pd
df = pd.DataFrame({"age": [25, np.nan, 31, 40, np.nan, 52]})
train = df.iloc[:4]
test = df.iloc[4:]
median = train["age"].median()
train = train.assign(age=train["age"].fillna(median))
test = test.assign(age=test["age"].fillna(median))
print(train["age"].tolist(), test["age"].tolist())Filling also shrinks the spread of a column, because every filled row sits at the same value. Standard deviations and correlations computed afterwards are too small. If those statistics matter, report them on the unfilled data or use a method that keeps variation.
Placeholders you did not convert
A sentinel such as -999 or "?" that was not turned into NaN at load time is treated as real data. It pulls means down, and isna reports zero missing values. After loading, scan each column with describe() and value_counts() for suspicious minimums or repeated odd strings. Fix them with na_values in read_csv, or df.replace(-999, np.nan).
Summary table
| Pitfall | Symptom | Fix |
|---|---|---|
| `== np.nan` | Filter matches nothing or everything | `isna()`, `notna()` |
| All-missing sum | `0.0` instead of `NaN` | `sum(min_count=1)` |
| Default `dropna()` | Almost all rows vanish | `subset=`, `thresh=`, check row counts |
| `inplace=True` on a column | Data unchanged, warning | Assign the result back |
| Integer column with gaps | Values become `3.0`, booleans become `object` | Nullable dtypes, `convert_dtypes()` |
| `if pd.NA` | `TypeError` | `pd.isna()`, `fillna(False)` |
| `groupby` on missing keys | Rows missing from totals | `dropna=False` or fill the key |
| `merge` on missing keys | Unrelated rows paired | Drop missing keys first |
| Full-data statistics | Leakage into test data | Fit on training rows only |
| Unconverted sentinels | Wrong means, no missing found | `na_values`, `replace` |
A checklist before you clean
Exercises
Exercise
A DataFrame has an integer column qty with one missing value, which pandas stored as float64. You call df["qty"] = df["qty"].fillna(0) and then export to CSV. The file contains 5.0 instead of 5. Give two ways to get whole numbers in the output.
Show answer
Fill first and then convert: df["qty"] = df["qty"].fillna(0).astype("int64"). Alternatively, convert to the nullable dtype before or after loading with df["qty"] = df["qty"].astype("Int64"). The column keeps integers and still allows missing values, so fillna(0) is then optional.
Exercise
Two tables are joined with left.merge(right, on="customer_id"). Both contain rows with a missing customer_id, and the result has more rows than expected. What is happening, and how do you prevent it?
Show answer
pandas matches missing keys on the two sides with each other, unlike SQL, so unrelated rows with missing IDs are paired. Remove them first with dropna(subset=["customer_id"]) on both tables before merging, then check the row count of the result.
Exercise
Why does pd.Series([np.nan, np.nan]).sum() return 0.0, and what argument makes it return NaN?
Show answer
sum skips missing values by default, and the sum of no values is zero. Passing min_count=1 requires at least one non-missing value, otherwise the result is NaN.