Skip to content Skip to sidebar Skip to footer

Groupby Id To Calculate Ratios

Objective I have this df and take some ratios below. I want to calculate these ratios by each id and datadate and I believe the groupby function is the way to go, however I am not

Solution 1:

Is this what you're looking for?

df = df.groupby(by=['id'], as_index=False).sum()
df['capital_ratioa'] = df['dltt']/(df['dltt']+df['ceq']+df['pstk'])
df['equity_invcapa'] = df['ceq']/df['icapt']
df['debt_invcapa'] = df['dltt']/df['icapt']
df['sale_invcapa']=df['sale']/df['icapt']
df['totdebt_invcapa']=(df['dltt']+df['dlc'])/df['icapt'] 
print(df)

Output:

     id  dltt     ceq      pstk  icapt   dlc       sale  capital_ratioa  equity_invcapa  debt_invcapa  sale_invcapa  totdebt_invcapa
0  1004  20.0  1538.0  4.805383      7  0.91  34.410577        0.012797      219.714286      2.857143      4.915797         2.987143
1  1005   9.0  2334.0  4.805383     18  1.05  34.410577        0.003833      129.666667      0.500000      1.911699         0.558333
2  1006  17.0  1320.0  4.805383     10  0.96  34.410577        0.012669      132.000000      1.700000      3.441058         1.796000

Post a Comment for "Groupby Id To Calculate Ratios"