Home > other >  Filtering, replacing and reappending a column to base df in pandas
Filtering, replacing and reappending a column to base df in pandas

Time:07-06

Imagine the following dataframe

Base dataframe

df  = pd.from_dict({'a': [1,2,1,2,1]
 'b': [1,1,3,3,1]
})

And them i pick up the a, column and replace a few values based on b column values

df.loc[df['b']== 3]['a'].replace(2,1)

How could i reappend my a column to my original df, but only changing those specific filtered values?

Wanted result

df  = pd.from_dict({'a': [1,2,1,1,1]
     'b': [1,1,3,3,1]
    })

CodePudding user response:

Do with update

df.update(df.loc[df['b']== 3,['a']].replace(2,1))
df
Out[354]: 
     a  b
0  1.0  1
1  2.0  1
2  1.0  3
3  1.0  3
4  1.0  1

CodePudding user response:

You can try df.mask

df['a'] = df['a'].mask(df['a'].eq(2) & df['b'].eq(3), 1)
print(df)

   a  b
0  1  1
1  2  1
2  1  3
3  1  3
4  1  1
  • Related