The 6 AI Engineering Patterns, come build with Greg live:Β Starts Jan 6th, 2025
Leverage
Pandas functions

Pandas Where – pd.DataFrame.where()

Pandas where to replace values based on condition

Pandas Where will replace values where your condition is False. It is useful when you have values that do not meet a criteria, and they need replacing.

We don’t often use this function, but it can be a handy one liner instead of iterating through a DataFrame or Series with.apply()

1. pd.DataFrame.where(cond=condition_to_check, other="Value To Fill")

Pseudo code: Where a condition is false, replace a value.

Pandas Where

Where

.where() has two main parameters, cond and other. Both of these are flexible to take Series, DataFrame or callable.

  • cond: Which stands for condition. This can either be a Series, DataFrame, or callable (function). WHERE this condition is false, pandas will replace values. I know, it’s a bit counter intuitive.
  • Other What to replace your values with. This again can be a scalar (single value), Series, DataFrame, or callable.
  • Other Parameters: To check out the other parameters that are not used that often, see the official documentation.

Let’s run through each iteration of the above parameters

Link to code

Official Documentation

On this page