简体   繁体   中英

Replace value in column based on multiple conditions in Pandas

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM