Home > Blockchain >  Replace value in column based on multiple conditions in Pandas
Replace value in column based on multiple conditions in Pandas

Time:12-02

I have this dataframe

df = pd.DataFrame.from_dict(
    {
        'Name': ['Jane', 'Melissa', 'John', 'Matt'],
        'Age': [23, 45, 35, 64],
        'Birth City': ['London', 'Paris', 'Toronto', 'Atlanta'],
        'Gender': ['F', 'F', 'M', 'M']
    }
)

and I want to replace the Gender to X, when the name is Melissa or John. How would I do this?

CodePudding user response:

A possible solution:

df['Gender'] = df['Gender'].mask(df['Name'].isin(['Melissa', 'John']), other='X')

Output:

      Name  Age Birth City Gender
0     Jane   23     London      F
1  Melissa   45      Paris      X
2     John   35    Toronto      X
3     Matt   64    Atlanta      M

CodePudding user response:

Here is my solution:

df.loc[((df['Name'] == 'Melissa') | (df['Name'] == 'John')), 'Gender'] = 'X'

And output

      Name  Age Birth City Gender
0     Jane   23     London      F
1  Melissa   45      Paris      X
2     John   35    Toronto      X
3     Matt   64    Atlanta      M
  • Related