如何在groupby pandas之后计算组内的值

时间:2017-02-05 23:21:22

标签: python pandas group-by

假设我有一个pandas DataFrame:

a   b   c  d  .... z
1   10  3  .
1   20  4  .
2   30  5  .
3   40  6  .
3   50  7  .  ....  .

我想制作一个DataFrame:

a    *not sure how to refer to this column?*
1   (10+20)/(3+4)  
2   30/5
3   (40+50)/(6+7)

我该怎么做?另外,如何引用创建的列?

我尝试了df.groupby(' a')但后来我不知道如何在熊猫中写下我想要的东西。

1 个答案:

答案 0 :(得分:3)

试试这个:

In [216]: df.groupby('a').apply(lambda x: x['b'].sum()/x['c'].sum())
Out[216]:
a
1    4.285714
2    6.000000
3    6.923077
dtype: float64