Common mistakes
A short tour of the classic Pandas traps and how to sidestep them.
In this page:
Common mistakes
Frequent errors include chained assignment (df[mask]["c"] = 1), which may not modify the original, ignoring the SettingWithCopy warning, and iterating with loops.
Others are forgetting that many methods return new objects, comparing with == against NaN, and losing rows in joins. Use loc for assignment and check shapes after merges.
Note:
Use df.loc[mask, "c"] = 1 for reliable assignment.
Example: Common mistakes
import numpy as np
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [0, 0, 0]})
df.loc[df["a"] > 1, "b"] = 99
print(df)
print(np.nan == np.nan, pd.isna(np.nan))
df.sort_values("a", ascending=False) # returns a copy, df is unchanged
print(df["a"].tolist())
# Output:
# a b
# 0 1 0
# 1 2 99
# 2 3 99
# False True
# [1, 2, 3]
Related Topics
Common Mistakes
- Chained assignment
- Assuming methods work in place
- Not checking row counts after a merge
Chapter Summary
- Use loc for assignment
- Most methods return copies
- NaN never equals NaN
- Check shapes after joins
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: