Home > Net >  Pandas change value based on other column values
Pandas change value based on other column values

Time:07-28

I want to change the value of each item in the column 'ageatbirth' to '1' if the 'race' is 2. In pseudocode:

If 'race' == 2 and 'ageatbirth' == 2:

'ageatbirth' == 1 

Is there an easy way to do this for a very large dataset?

CodePudding user response:

Use

m = df['race'].eq(2) & df['ageatbirth'].eq(2)

df['ageatbirth'] = df['ageatbirth'].mask(m, 1)
# or
df.loc[m, 'ageatbirth'] = 1
  • Related