← Back to Pandas Course | Chapter 13: Performance & Best Practices | Lesson 6 of 6

Common mistakes

A short tour of the classic Pandas traps and how to sidestep them.

In this page:

  1. Common mistakes

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

python
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
  1. Chained assignment
  2. Assuming methods work in place
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.