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:

iddlttceqpstkicaptdlcsalecapital_ratioaequity_invcapadebt_invcapasale_invcapatotdebt_invcapa01004  20.01538.0  4.80538370.9134.4105770.012797219.7142862.8571434.9157972.98714311005   9.02334.0  4.805383181.0534.4105770.003833129.6666670.5000001.9116990.55833321006  17.01320.0  4.805383100.9634.4105770.012669132.0000001.7000003.4410581.796000

Post a Comment for "Groupby Id To Calculate Ratios"