pandas groupby在列上聚合,并将组大小合并到数据框中

时间:2019-06-20 16:29:14

标签: python python-3.x pandas dataframe pandas-groupby

我有一个df

code    y_m       day_1     day_2
13      201906    30        40
13      201906    10        20
14      201903    20        40
14      201903    20        30

我想创建一列

df['delta'] = df['day_2'] - df['day_1']

code    y_m       day_1     day_2    delta
13      201906    30        40       10 
13      201906    10        20       10
14      201903    20        40       20
14      201903    20        30       10

然后groupby codey_m,将增量相加,并同时将组大小放入另一个数据帧中;但是

df.groupby(['code', 'y_m']).size().reset_index(name = 'count')

仅获取组大小;那么如何将delta也汇总到同一数据框中;

code    y_m       delta    count
13      201906    20        2
14      201903    30        2

0 个答案:

没有答案