Skip to main content

StepFilter

Remove rows that do not match a predicate.

Usage

Source

StepFilter(
    predicate,
    *,
    id=None,
)

Rows for which predicate is not True are dropped. To add or change columns instead, see StepMutate.

Filtering applies to the training data only. Fitting a recipe drops the non-matching training rows, but transforming new data returns every row given to it, because dropping rows from data being scored would silently lose predictions. So a recipe that filters is not a way to filter new data.

See Arguments shared across steps for the arguments this step shares with the others.

Parameters

predicate: Predicate

Callable taking the data frame and returning a boolean narwhals expression or series, True for the rows to keep. Must be callable.

id: str | None = None
Stable step identifier. Defaults to "filter"; a second step of this type in the same recipe becomes "filter_2", and passing an id already used in the recipe is an error.

Examples

Rows where age is 30 or below are dropped when the recipe is fitted, while transform() leaves every row in place:

df = pd.DataFrame({"age": [25, 41, 33, 52]})
df
age
0 25
1 41
2 33
3 52

Specifying the step touches no data:

recipe = Recipe().add(StepFilter(lambda df: df["age"] > 30))
recipe
Recipe (untrained)
  Inputs: no roles assigned
  Steps:
    step_filter()  [untrained]

fit() applies the predicate to the training data:

fitted = recipe.fit(df)
fitted
Recipe (trained)
  Inputs: 1 columns (1 feature)
  Steps:
    step_filter(age)  [trained]

transform() leaves new data untouched, so all four rows come back:

fitted.transform(df)
age
0 25
1 41
2 33
3 52