skip to content

In pandas, how do DataFrame.where and DataFrame.mask differ from filtering with df[mask], and what happens to an int64 column?

level: middleimportance: should knowfreq 45%

answer

  1. shape kept versus rows dropped
  2. keep where true, replace where true
  3. default replacement is missing
  4. integers cannot hold NaN

basics

~20 s

df[mask] drops non-matching rows; where and mask keep the full shape and index, replacing values instead. where keeps values where the condition is True, mask replaces them; without other, int64 becomes float64 to hold NaN.

solid answer

~40 s

Filtering with `df[mask]` returns only the matching rows. `where(cond, other)` returns the same shape and index, keeping each value where `cond` is `True` and putting `other` where it is `False`; `mask` does the reverse. Without `other`, replaced cells get the dtype's missing value, `np.nan` for NumPy dtypes or `pd.NA` for extension dtypes, so an `int64` column comes back as `float64`, while `Int64` stays `Int64` with `<NA>`. An explicit `other` is cast to the column's dtype only when that is lossless: `where(cond, 0)` stays `int64`, `where(cond, 0.5)` becomes `float64`. A boolean Series condition on a frame applies to every column, and `df[df > 0]` with a boolean frame is `where` under the hood.

code

python · 16 lines
python
import pandas as pd

delays = pd.DataFrame(
    {"dep_delay": [5, 42, 0], "arr_delay": [2, 50, -3]},
    index=[101, 102, 103],
)
late = delays["dep_delay"] > 15

print(delays[late])                      # one row: 102
print(delays.where(late))                # three rows, 101 and 103 all NaN, float64
print(delays.mask(late))                 # three rows, 102 is NaN

arr = delays["arr_delay"]
print(arr.mask(arr < 0, 0).tolist(), arr.mask(arr < 0, 0).dtype)   # [2, 50, 0] int64
print(arr.where(arr > 0).dtype)                                     # float64
print(arr.astype("Int64").where(arr > 0).tolist())                 # [2, 50, <NA>]

go deeper

for a junior

Recall that where keeps values where the condition is True and mask replaces them, and that both keep every row, unlike df[mask].

for a middle

Explain the default fill, NaN or pd.NA by dtype, the int64 to float64 change, the lossless-cast rule for other, and how a row condition broadcasts across a frame's columns.

for a senior

Show when a shape-preserving replacement beats filtering, such as masking outliers before an aggregate, and how label alignment of the condition can blank rows silently.

for a principal

Weigh the readability of where against mask in shared code: pick the one whose condition reads positively, and keep dtype changes visible in review.

## Filtering changes the shape; `where` and `mask` do not pandas offers two ways to act on a boolean condition, and they answer different questions: - **`df[row_mask]`** answers "which rows do I keep?" It returns fewer rows, with the original index labels of the survivors. - **`df.where(cond)`** answers "which values do I keep?" It returns an object of the **same shape and index**, keeping each value where `cond` is `True` and replacing it where `cond` is `False`. - **`df.mask(cond)`** is the mirror image: it replaces each value where `cond` is `True` and keeps it where `cond` is `False`. | Call | Rows returned | Values where `cond` is True | Values where `cond` is False | |---|---|---|---| | `df[cond]` (row mask) | only matching rows | kept | row dropped | | `df.where(cond)` | all rows | kept | replaced by `other` | | `df.mask(cond)` | all rows | replaced by `other` | kept | Both methods live on `Series` and `DataFrame` with the signature `where(cond, other=..., *, inplace=False, axis=None, level=None)`, and both return a new object. ## What fills the replaced cells When `other` is not given, the replaced cells hold the dtype's **missing value**: `np.nan` for NumPy dtypes and `pd.NA` for extension dtypes such as `Int64`. That has a dtype consequence that surprises people: 1. An `int64` column cannot hold `NaN`, so `s.where(s > 15)` returns **`float64`**, and `42` prints as `42.0`. 2. A nullable `Int64` column stays `Int64` and shows `<NA>` in the replaced cells. 3. With an explicit `other`, the docstring's rule applies: the object's dtype takes precedence, and `other` is cast to it **if that can be done losslessly**. `s.where(s > 15, 0)` stays `int64`; `s.where(s > 15, 0.5)` becomes `float64`. `other` can also be a Series, a DataFrame or a callable, so `df.where(df > 0, -df)` flips the sign of the non-positive values only. ## Shapes of the condition - **Same-shaped boolean DataFrame.** `df.where(df > 0)` decides cell by cell. Indexing with a boolean frame, `df[df > 0]`, is implemented with `where` and returns the same result. - **A boolean Series on a DataFrame.** `df.where(df['dep_delay'] > 15)` applies the row condition to every column, so whole rows turn to `NaN` while the frame keeps its shape. - **A callable.** `s.where(lambda x: x > 0)` computes the condition from the object itself, which suits method chains. - **Misaligned labels.** The condition aligns on labels; positions it does not cover count as `False`, so those values are replaced. ## Callables for `cond` and `other` Both arguments accept a function that receives the calling object: - `s.where(lambda x: x > 0)` builds the condition from the Series itself, so the call works in a chain where the intermediate object has no name. - `df.where(df > 0, lambda d: -d)` computes the replacement from the caller too. - The docstring adds one rule: the callable **must not change** the input object, and pandas does not check it, so a function with side effects can corrupt data silently. ## Argument order versus `numpy.where` `Series.where` keeps the caller where the condition holds; `numpy.where` picks between two inputs. The user guide states the equivalence: ```python df1.where(m, df2) # pandas np.where(m, df1, df2) # NumPy, roughly equivalent ``` `np.where` returns a NumPy array without the index, so the pandas method is the one that keeps labels and dtype rules. ## When to reach for which - **Reports and summaries over a subset**: filter with `df[mask]`; the dropped rows should not exist downstream. - **Feature columns, capping and cleaning that keep row alignment**: `where` or `mask`, so every row stays and lines up with the rest of the table. - **Masking outliers before an aggregate**: `s.mask(s > 300)` turns extreme delays into `NaN`, and most reductions then skip them. - **Readability**: choose the method whose condition you can state positively. `s.mask(s < 0, 0)` ("replace negatives with zero") reads better than `s.where(s >= 0, 0)`, though both give the same values. Writing the result back into the original frame is a separate step, covered with assigning values. ## Mistakes to avoid - Expecting `where` to drop the rows whose condition is `False`. - Mixing up the direction: `where` keeps `True`, `mask` replaces `True`. - Expecting an `int64` column to stay `int64` after `where` without `other`. - Reading `s.where(cond, other)` with `numpy.where`'s argument order.

  • How do you replace negative arrival delays with 0 while keeping every row and the int64 dtype?
    `arr.mask(arr < 0, 0)` replaces exactly the negative values; `arr.where(arr >= 0, 0)` is the same. Because 0 fits `int64` losslessly, the dtype stays `int64`. Leaving out `other` would fill `NaN` and turn the column into `float64`.
  • How does Series.where's argument order differ from numpy.where?
    `s.where(cond, other)` keeps `s` where `cond` is True and uses `other` elsewhere. `np.where(cond, a, b)` picks `a` where True and `b` where False, so `s.where(cond, other)` is roughly `np.where(cond, s, other)`. The pandas call also keeps the index and the dtype rules.
  • What happens when the condition Series lacks some of the frame's index labels?
    `where` aligns the condition on labels and treats every uncovered position as `False`, so those values are replaced with `other` or the missing value. Build the condition from the same object to avoid silently blanked rows.

Filtering is cutting rows out of a printed table, so the page gets shorter; where and mask black out cells with a marker, so every row is still there in its place, just partly redacted.

  • Expecting where to drop the rows where the condition is False
  • Believing where replaces values where the condition is True
  • Expecting an int64 column to stay int64 after where with no other
  • Reading s.where(cond, other) with numpy.where's argument order
  • Thinking df[df > 0] with a boolean frame drops rows