Python 熊猫:比较两个时间段的总和?

Python 熊猫:比较两个时间段的总和?,python,pandas,Python,Pandas,我有一个如下所示的数据帧: prod_code month items cost 0 040201060AAAIAI 2016-05-01 5 572.20 1 040201060AAAKAK 2016-05-01 164 14805.19 2 040201060AAALAL 2016-05-01 13465 14486.07 cost para month 0402

我有一个如下所示的数据帧:

         prod_code      month  items      cost
0  040201060AAAIAI 2016-05-01      5    572.20   
1  040201060AAAKAK 2016-05-01    164  14805.19    
2  040201060AAALAL 2016-05-01  13465  14486.07  
                 cost
para month
0402 2016-01-01    84
     2016-02-01    93
     2016-03-01   105
0403 2016-01-01    20
     2016-02-01    24
     2016-03-01    23
我想首先根据
产品代码的前四个字符进行分组,然后计算2016年1月至2月各组的总成本,然后将其与2016年3月至4月的总成本进行比较,然后找出两个时间段内增长百分比最大的组

最好的办法是什么

以下是我目前的代码:

d = { 'prod_code': ['040201060AAAIAI', '040201060AAAIAJ', '040201060AAAIAI', '040201060AAAIAI', '040201060AAAIAI', '040201060AAAIAI', '040301060AAAKAG', '040301060AAAKAK', '040301060AAAKAK', '040301060AAAKAX', '040301060AAAKAK', '040301060AAAKAK'], 'month': ['2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01'], 'cost': [43, 45, 46, 41, 48, 59, 8, 9, 10, 12, 15, 13] }
df = pd.DataFrame.from_dict(d)
df['para'] = df.prod_code.str[:4]
df_para = df.groupby(['para', 'month']).sum()
这给了我
df_para
,看起来像这样:

         prod_code      month  items      cost
0  040201060AAAIAI 2016-05-01      5    572.20   
1  040201060AAAKAK 2016-05-01    164  14805.19    
2  040201060AAALAL 2016-05-01  13465  14486.07  
                 cost
para month
0402 2016-01-01    84
     2016-02-01    93
     2016-03-01   105
0403 2016-01-01    20
     2016-02-01    24
     2016-03-01    23

现在我需要计算每个组1-2月和4-3月的总和,然后计算这两组之间的差值,最后根据这两组之间的差值进行排序。最好的方法是什么?

您可以根据月份是
Jan-Feb
还是
Mar-Apr
创建月份组变量,然后根据代码和月份组变量进行分组,汇总成本并计算差异:

import numpy as np
import pandas as pd
df['month_period'] = np.where(pd.to_datetime(df.month).dt.month.isin([1,2]), 1, 2)
# creation of the month group variable could be adjusted based on how you want to cut 
# your time, this is a simplified example which assumes you only have data from Jan-Apr

(df.groupby([df.prod_code.str[:4], df.month_period]).sum().groupby(level = 0).pct_change()
   .dropna().sort('cost', ascending=False))

您能提供可复制的输入和所需的数据集吗?谢谢,这看起来很棒!事实上,我有五年的数据,只想将2010年1月-6月和2015年1月-6月进行比较——最好的方法是什么?虚拟变量可能需要三个值——第一个周期为1,第二个周期为2,其他所有值为null,但是我如何计算仅在1和2之间的
pct_变化量呢?如果其他所有值都设置为0,然后,您可以在计算
pct\u更改之前过滤掉所有0条记录,或者它为每个组返回两个pct\u更改,第二个应该是您要查找的。我可能只会过滤掉不在您感兴趣的日期范围内的记录。类似于
cond1=(df.month>'2010-01-01')&(df.month<'2010-06-30');cond2=(df.month>2015-01-01')和(df.month<2015-06-30');df['month_period']=np.where(cond1,1,np.where(cond2,2,0));df=df[df.month\u period!=0]