Unlike boolean indexing, which returns a smaller DataFrame containing only the matching rows, where() returns a DataFrame of the exact same shape as the original, with values that fail the condition replaced, by default with NaN, rather than dropped entirely — this makes it well suited for masking out invalid values in place while keeping every row and column aligned for further calculations. Passing the other parameter lets you substitute a specific value or another DataFrame's aligned values instead of the default NaN.
1Understanding df.where()
Unlike boolean indexing, which returns a smaller DataFrame containing only the matching rows, where() returns a DataFrame of the exact same shape as the original, with values that fail the condition replaced, by default with NaN, rather than dropped entirely — this makes it well suited for masking out invalid values in place while keeping every row and column aligned for further calculations. Passing the other parameter lets you substitute a specific value or another DataFrame's aligned values instead of the default NaN.
Use where() specifically when you need to keep the DataFrame's original shape and replace non-matching values in place, rather than boolean indexing, which instead drops non-matching rows entirely and returns a smaller result.
import pandas as pd
df = pd.DataFrame({"score": [55, 90, 45, 80]})
print(df.where(df["score"] >= 60))2Practical Example
Here is a real-world application of df.where() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"score": [55, 90, 45, 80]})
print(df.where(df["score"] >= 60, other=0))3Best Practices
Follow these guidelines when working with df.where():
1. Use where() when downstream code needs the DataFrame's shape preserved, like for aligned arithmetic with another DataFrame, instead of boolean indexing which shrinks it
2. Pass an explicit other value when NaN isn't the right substitute for values that fail the condition
3. Use boolean indexing instead of where() when you actually want a smaller, filtered DataFrame rather than a same-shaped one with replaced values
Tip: Use where() specifically when you need to keep the DataFrame's original shape and replace non-matching values in place, rather than boolean indexing, which instead drops non-matching rows entirely and returns a smaller result.
import pandas as pd
df = pd.DataFrame({"score": [55, 90, 45, 80]})
print(df.where(df["score"] >= 60))