Today I had a simple task: I have products, quantities and a dummy, and I needed to know which percentage of the total quantities of that product the dummy represented. My DataFrame looked like this:
Product Qty Dummy A 10 0 B 15 0 B 5 1 C 5 0 D 5 0 D 20 1
And I needed to get there:
Product Qty_pct B 0.25 D 0.8
So, I only needed the percentage when the dummy takes value = 1
I managed to do it, like this:
df2=df.pivot_table(columns='Dummy',index='Product',aggfunc='sum',values=['Qty']).reset_index() df2['Qty_pct']=df2['Qty']/(df4['Qty']+df2['Qty']) df2.columns=df2.columns.get_level_values(0)
To me it seems like a very indirect way to achieve my goal and I feel this can be done in a way more elegant way. What would you do?