Sub topic 13
Pitfalls to avoid
This chapter assumes you can create DataFrames, use isna, dropna, fillna and groupby, and know that np.nan is a float. It covers mistakes that run without errors but give wrong or surprising results.
Mistakes that look like they work
| Pitfall | What happens | Safer habit |
|---|---|---|
| `df["a"].fillna(0, inplace=True)` | May change a temporary copy, not `df` | Assign back: `df["a"] = df["a"].fillna(0)` |
| `df == np.nan` | Always `False`, because NaN is not equal to anything | Use `isna()` or `notna()` |
| `df.dropna()` with no arguments | Drops any row with any missing cell | Use `subset`, `how` or `thresh` |
| Integer column gains a missing value | Column becomes `float64` | Use `Int64` or `convert_dtypes()` |
| Merging on a key that has missing values | Missing keys match each other | Drop or fill the keys first |
| `groupby` on a key with missing values | Those rows vanish from the result | Pass `dropna=False` if you need them |
inplace and chained assignment
inplace=True does not make code faster, and it can silently fail when you call it on a column selected from a DataFrame. Recent pandas versions with copy-on-write never update the parent in that case. Assign the result back instead.
import numpy as np
import pandas as pd
df = pd.DataFrame({"age": [25, np.nan, 31]})
df["age"].fillna(0, inplace=True) # unreliable: may not change df
print(df["age"].tolist())
df["age"] = df["age"].fillna(0) # explicit and always works
print(df["age"].tolist())Merge keys that are missing
merge joins a missing key on the left to a missing key on the right. This differs from SQL, where NULL never equals NULL. It can create rows you did not expect.
import pandas as pd
left = pd.DataFrame({"key": ["a", None], "x": [1, 2]})
right = pd.DataFrame({"key": ["a", None], "y": [10, 20]})
print(left.merge(right, on="key"))
print(left.dropna(subset=["key"]).merge(right, on="key"))The first result has two rows, and the second has one. Check key columns with isna().sum() before you merge.
Silent type changes
Missing values force some dtypes to change. Integers become floats, and booleans become object. Later steps, such as writing IDs to a file, then show 3.0 instead of 3.
import pandas as pd
ids = pd.Series([1, 2, 3])
print(ids.shift().dtype) # float64: shift created a NaN
flags = pd.Series([True, None, False])
print(flags.dtype) # object
fixed = ids.shift().astype("Int64")
print(fixed)Filling does not always restore the original type. fillna(0) on a float column gives floats. Convert back with astype after the fill, or use a nullable dtype from the start.
Dropping too much
dropna() defaults to how="any". On a wide table, one sparse column can remove most of your rows. Compare sizes before and after.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"id": [1, 2, 3, 4],
"rare": [np.nan, np.nan, np.nan, 5.0],
"age": [20.0, 30.0, np.nan, 40.0],
})
print(df.shape, df.dropna().shape)
print(df.dropna(subset=["age"]).shape)The first call leaves one row. The second keeps three, because it only requires the column you need.
A quick checklist
- Count missing values per column before and after each step.
- Print
dtypesafter loading, filling, merging and shifting. - Never fill or drop on a column before you know why its values are missing.
- Assign results back. Do not use
inplace. - Record the choice you made, so the next reader can see it.
Exercise
A DataFrame has an integer column qty. You run df2 = df.merge(other, on="sku", how="left"), and qty is now float64 with some NaN. Give two likely causes and one way to restore integers.
Show answer
Some rows in df have no matching sku in other, or qty comes from other and the left join left unmatched rows empty. Either way, missing values force the integer column to float. Check the cause with df2["qty"].isna().sum() and a count of unmatched keys. Then restore integers with df2["qty"] = df2["qty"].astype("Int64"), which keeps the missing values as pd.NA. If the missing values should be zero, use df2["qty"].fillna(0).astype("int64").