Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
    })

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading