2016-12-02 77 views
2

所以在R當我有一個由4列組成的數據幀,稱之爲df,我想通過一個組的和產品計算比率,我可以這樣:Python熊貓平等地R groupby變異

// generate data 
df = data.frame(a=c(1,1,0,1,0),b=c(1,0,0,1,0),c=c(10,5,1,5,10),d=c(3,1,2,1,2)); 
| a b c d | 
| 1 1 10 3 | 
| 1 0 5 1 | 
| 0 0 1 2 | 
| 1 1 5 1 | 
| 0 0 10 2 | 
// compute sum product ratio 
df = df%>% group_by(a,b) %>% 
     mutate(
      ratio=c/sum(c*d) 
    ); 
| a b c d ratio | 
| 1 1 10 3 0.286 | 
| 1 1 5 1 0.143 | 
| 1 0 5 1 1  | 
| 0 0 1 2 0.045 | 
| 0 0 10 2 0.454 | 

但在Python中,我得到了循環。 我知道應該有比python中的原始循環更優雅的方式,任何人有任何想法?

回答

6

它可以與類似的語法來完成與groupby()apply()

df['ratio'] = df.groupby(['a','b'], group_keys=False).apply(lambda g: g.c/(g.c * g.d).sum()) 

enter image description here

+0

什麼的group_keys =假達到什麼目的? – asosnovsky

+1

默認情況下,'groupby()'將組列添加爲結果的額外索引,使索引與原始數據幀不同,因此不能輕鬆分配數據幀。避免添加組列,因爲只要每行具有唯一索引,鍵就可以進行分配。 – Psidom