2017-05-10 103 views
1

我有這樣GROUPBY和大熊貓數據幀百分制計算

name event spending 
abc A  500 
abc B  300 
abc C  200 
xyz A  2000 
xyz D  1000 

一個數據幀所以我需要一個GROUPBY名稱和事件,並計算相應的百分...所以輸出應該是這樣的

name event spending_percentile 
abc A  50% 
abc B  30% 
abc C  20% 
xyz A  66.67% 
xyz D  33.33% 

請指導如何在熊貓數據框中做到這一點。

+1

相關的和可能的欺騙:https://stackoverflow.com/questions/39388820/pandas-groupwise-percentage – EdChum

+0

@EdChum:對不起,沒有正確谷歌(被匆忙)..謝謝你,那個鏈接有幫助。 – Satya

回答

2

看來你需要transform

df['spending_percentile'] = df['spending'].div(df.groupby('name')['spending'] 
               .transform(sum)).mul(100) 
print (df) 
    name event spending spending_percentile 
0 abc  A  500   50.000000 
1 abc  B  300   30.000000 
2 abc  C  200   20.000000 
3 xyz  A  2000   66.666667 
4 xyz  D  1000   33.333333 
+0

偉大的幫助..謝謝@jezrael – Satya