Home > Blockchain >  Pandas DataFrame: Manipulate value in one column based von value in other column
Pandas DataFrame: Manipulate value in one column based von value in other column

Time:10-25

I got two Pandas DataFrames df and df_0:

df = pd.DataFrame({'condition': [1, 2, 3], 
                     'value': [1, 2, 3]})
df_0 = pd.DataFrame({'condition': [1, 2], 
                     'value': [1, 3]})
   condition  value
0          1      1
1          2      2
1          3      3
   condition  value
0          1      1
1          2      3

I want to subtract (-=) the value in df_0 from the value (column) in df, if the resp. condition value/column is the same.

Pseudo code 
df_desired_result = pd.DataFrame({'condition': [1, 2, 3], 
                     'value': [0, -1, 3]})

   condition  value
0          1      0
1          2     -1
2          3      3

How can I achiev this?

Thanks a lot in advance for your reply!

Lucy

CodePudding user response:

Pandas does an index wise arithmetic operations. just set the 'condition' to be the index, and then fill the NaN values

import pandas as pd
import numpy as np
df = pd.DataFrame({'condition': [1, 2, 3], 
                     'value': [1, 2, 3]})
df_0 = pd.DataFrame({'condition': [1, 2], 
                     'value': [1, 3]})
df_desired_result  = df.set_index('condition')-df_0.set_index('condition').reindex(df.condition,fill_value=0)
print(df_desired_result)
  • Related