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

How to update column value based on another value in pandas

I have the below data frame

| A | B|
|Jan|10|
|Feb|20|
|Mar|30|
|Apr|20|

Required Output – I want to check for March from A and get its corresponding value from B and add that value to remaining B values to update the dataframe using pandas

| A |B |
|Jan|40|
|Feb|50|
|Apr|50|

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

>Solution :

You can do it in one line, pandas-style, using set_index():

df = df.set_index('A').pipe(lambda x: x.assign(B=x['B'] + x.loc['Mar', 'B'])).drop('Mar').reset_index()

Output:

>>> df
     A   B
0  Jan  40
1  Feb  50
2  Apr  50

Or in multiple lines (not so pandas-style):

df['B'] += df.loc[df['A'] == 'Mar', 'B'].iloc[0]
df = df[df['A'] != 'Mar']

Or a third and slightly shorter way:

tmp = df.set_index('A').T
df = (tmp.pop('Mar').iloc[0] + tmp.T['B']).reset_index()
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