2014-01-18 142 views
1
类别

内的百分比我有一个数据帧像这样的(除了更多的行和大小,说):熊猫:

size amount 
1 big  1 
2 big  9 
3 small  3 
4 small  1 

,我想获得这样的数据帧,其中amountPct是金额除以相同大小的金额总和。

size amountPct 
1 big  0.10 
2 big  0.90 
3 small  0.75 
4 small  0.25 

我可以重塑数据帧,将通过总和为每个尺寸,然后重塑其返回到原来的形状做到这一点,但有这样做的更优雅的方式?

PS:我问了同样的问题R,但现在我想大熊猫的答案!

+0

这是问题中的R版本:http://stackoverflow.com/questions/21195651/percentage-within-category – nicolaskruchten

回答

2

怎么是这样的:

df = pd.DataFrame({'size':['big', 'big', 'small', 'small'], 'amount':[1, 9, 3, 1]}) 
df['pct'] = df.groupby('size')['amount'].apply(lambda x: x.astype(float)/x.sum()) 
+0

在0.13.1,这将被列入通过排名(将更快):https://github.com/pydata/pandas/pull/5978 – Jeff

+0

所以这个作品,谢谢,但我无法理解为什么...你能解释一下吗?在'lambda'中,什么是'x'? – nicolaskruchten

+0

@nicolaskruchten在这种情况下x是'金额'列 – EdChum