four-eyes
four-eyes

Reputation: 12469

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?

Upvotes: 1

Views: 129

Answers (2)

swifferlifterupper
swifferlifterupper

Reputation: 31

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

Upvotes: 3

PaulS
PaulS

Reputation: 25528

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

Upvotes: 2

Related Questions