mask() and where() are complementary: where(cond) keeps values where cond is True and replaces the rest, while mask(cond) replaces values where cond is True and keeps the rest — calling mask() with a condition produces exactly the same result as calling where() with that same condition negated. It's useful when it's more natural to express the condition for what you want to remove or mask out, rather than what you want to keep.
1Understanding df.mask()
mask() and where() are complementary: where(cond) keeps values where cond is True and replaces the rest, while mask(cond) replaces values where cond is True and keeps the rest — calling mask() with a condition produces exactly the same result as calling where() with that same condition negated. It's useful when it's more natural to express the condition for what you want to remove or mask out, rather than what you want to keep.
df.mask(cond) is exactly equivalent to df.where(~cond) — pick whichever one lets you express your actual condition more naturally, rather than always writing an awkward double-negative to force one into the other.
import pandas as pd
df = pd.DataFrame({"temperature": [72, 105, 68, 98]})
print(df.mask(df["temperature"] > 100))2Practical Example
Here is a real-world application of df.mask() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"temperature": [72, 105, 68, 98]})
print(df.mask(df["temperature"] > 100, other=100))3Best Practices
Follow these guidelines when working with df.mask():
1. Use mask() when the condition naturally describes what should be replaced/hidden, and where() when it naturally describes what should be kept, for whichever reads more clearly
2. Pass an explicit other value to mask() when NaN isn't the right substitute for the masked-out positions
3. Remember mask()'s and where()'s condition roles are exact opposites of each other — double check which one matches your actual intent before using either
Tip: df.mask(cond) is exactly equivalent to df.where(~cond) — pick whichever one lets you express your actual condition more naturally, rather than always writing an awkward double-negative to force one into the other.
import pandas as pd
df = pd.DataFrame({"temperature": [72, 105, 68, 98]})
print(df.mask(df["temperature"] > 100))