Replace column value based on value in other column

you can use 2 boolean conditions and use loc:

df.loc[df['Area'].eq("Q") & df['Stage'].eq('X'),'Area']='P'
print(df)

   ID Area Stage
0   1    P     X
1   2    P     X
2   3    P     X
3   4    Q     Y

Or np.where

df['Area'] = np.where(df['Area'].eq("Q") & df['Stage'].eq('X'),'P',df['Area'])

Could you please try following.

import pandas as pd
import numpy as np
df['Area']=np.where(df['Stage']=='X','P',df['Area'])

You can use loc to specify where you want to replace, and pass the replaced series to the assignment:

df.loc[df['Stage']=='X', 'Area'] = df['Area'].replace('Q','P')

Output:

   ID Area Stage
0   1    P     X
1   2    P     X
2   3    P     X
3   4    Q     Y

Tags:

Python

Pandas