如何轻松进行累积均值和计数

时间:2019-09-01 14:56:21

标签: python-3.x pandas

我在熊猫中有以下数据框

data = {'call_put':['C', 'C', 'P','C', 'P'],'price':[10,20,30,40,50], 'qty':[11,12,11,14,9]}
df['amt']=df.price*df.qty
df=pd.DataFrame(data)


call_put    price   qty amt
0   C   10  11  110
1   C   20  12  240
2   P   30  11  330
3   C   40  14  560
4   P   50  9   450

我想根据call_put值输出如下内容,例如“ C”或“ P”计数,中位数和计算结果

call_put price  qty amt      cummcount    cummmedian               cummsum           

C   10  11  110      1            110                       110
C   20  12  240      2            175    ((110+240)/2 )     350  
P   30  11  330      1            330                       680
C   40  14  560      3            303.33 (110+240+560)/3   1240
P   50  9   450      2            390 ((330+450)/2)        1690

是否可以通过简单的方式完成操作而无需创建其他数据框和功能?

3 个答案:

答案 0 :(得分:1)

创建名为g的分组元素,然后使用df.assign分配值:

g=df.groupby('call_put')
final=df.assign(cum_count=g.cumcount().add(1),
   cummedian=g['amt'].expanding().mean().reset_index(drop=True), cum_sum=df.amt.cumsum())

  call_put  price  qty  amt  cum_count   cummedian  cum_sum
0        C     10   11  110          1  110.000000      110
1        C     20   12  240          2  175.000000      350
2        P     30   11  330          1  303.333333      680
3        C     40   14  560          3  330.000000     1240
4        P     50    9  450          2  390.000000     1690

注意:对于Pcummedian应该为390,因为(330 + 450)/ 2 = 390

对于cum_count,请查看df.groupby.cumcount()cummedian检查expanding()的工作方式, 用于累积检查df.cumsum()

答案 1 :(得分:0)

IIUC,这应该可以工作

df['cumcount']=df.groupby('call_put').cumcount()

df['cummidean']=df.groupby('call_put')['amt'].cumsum()

df['cumsum']=df.groupby('call_put').cumsum()

答案 2 :(得分:0)

感谢以下解决方案很好

g = df.groupby('call_put') final = df.assign(cum_count = g.cumcount()。add(1),    cummedian = g ['amt']。expanding()。mean()。reset_index(drop = True),cum_sum = df.amt.cumsum())

  1. 如果我在没有drop = True的情况下进行关注

g ['amt']。expanding()。mean()。reset_index()

为什么输出显示level_1

call_put    level_1 amt

0 C 0 110.000000 1 C 1 175.000000 2 C 3 303.333333 3 P 2 330.000000 4 P 4 390.000000

g ['amt']。expanding()。mean()。reset_index(drop = True)

0 110.000000 1 175.000000 2 303.333333 3330.000000 4 390.000000 名称:amt,dtype:float64

您能详细解释一下吗?

  1. 如何在groupby子句中添加一个条件

g = df.groupby('call_put','price'<50)

TypeError:“ str”和“ int”的实例之间不支持“ <”