Pandas DataFrame where() method with examples

Spread the love

In Pandas, the Where() method is used to replace values where the condition is False. When the condition is True, the where method keeps the original values and when the condition is False, the where method replace original values with the values specified in the other argument.

Syntax –

df.where(cond,other=nan)

Let’s create a dataframe to illustrate it.

import pandas as pd

data = {'Apple':[89, 89, 90, 110, 125, 84, 131, 123, 123, 140, 145, 145],
       'Orange': [46, 46, 50, 65, 63, 48, 110, 120, 60, 42, 47, 62],
       'Banana': [26, 30, 30, 25, 38, 22, 22, 36, 20, 27, 23, 34 ],
       'Mango': [80, 80, 90, 125, 130, 150, 140, 140, 135, 135, 80, 90]}

index = ['Jan','Feb','Mar','Apr','May','June','Jul','Aug','Sep','Oct','Nov','Dec']
df = pd.DataFrame(data, index=index)
df

Here we have fruit prices of various fruits for different months.

Examples –

1 . Replace Values in the Entire DataFrame –

Let’s say we want to replace all the value which is greater than 100 with ‘high‘ price. For this we will write.

df.where(df < 100, other='high')

Similarly we can perform the opposite of it. Let’s say we want to replace all the values that is less than 100 with ‘low‘ and keep the values that is higher than 100 as it is.

df.where(df > 100, other='low')

2 . Replace Values in a Specific Column –

We can also replace values that don’t meet certain condition in a specific column of a dataframe.

Let’s say we don’t want to sell Mangoes in the Month where the prices are low (i.e. the prices are less than 100).

df['Mango'] = df['Mango'].where(df['Mango'] > 100, other='Not Selling')
df

Here, we are keeping all the values that are greater than 100 and replacing all the values that don’t meet the condition with ‘Not Selling‘.

Rating: 1 out of 5.

Leave a Reply