Home > Back-end >  How to make calculation between 2 dataframes by row and column position in an effective way?
How to make calculation between 2 dataframes by row and column position in an effective way?

Time:07-04

I am trying to derive a new dataframe from 2 existing ones that calculates the percentage difference between the 2 existing dfs by row & column position. This is how the 2 dfs look like:

df1:
period_number   0      1        2   
0               1.0    0.55    0.35
1               1.0    0.40    0.20

df2:
period_number   0      1       2    
0               1.0    0.30    0
1               1.0    0.20    0

df_master (Note: df1 is the baseline for the percentage calculation against df2):
period_number   0           1                  2    
0               (1-1)/1    (0.55-0.3)/0.55     (0.35-0)/0.35
1               (1-1)/1    (0.40-0.2)/0.4      (0.20-0)/0.2

I tried merging but the format is just very hard to bring it to such calc, so not sure I need to combine pd.merge with something else?

CodePudding user response:

df_master = (df1 - df2) / df1
df_master['period_number'] = df1.period_number
  • Related