Home > OS >  How to update column value based on another value in pandas
How to update column value based on another value in pandas

Time:02-05

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

CodePudding user response:

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()

CodePudding user response:

You can find the value corresponding to 'Mar', add that value to the rest of the df, then drop the row containing 'Mar'

df.loc[df['A'] != 'Mar','B']  = df.loc[df['A'] == 'Mar', 'B'].values
df = df[df['A'] != 'Mar']

Result:

>>> df
     A   B
0  Jan  40
1  Feb  50
3  Apr  50
  •  Tags:  
  • Related