Skip to main content
 首页 » 编程设计

python之Groupby、Shift 和 Sum

2024年11月24日6zhoujg

我有以下数据框:

product    Week_Number       Sales 
1               1              10 
2               1              15 
1               2              20 

我想按产品和周数分组,并创建一个包含该产品下周销售额的列:

product    Week_Number       Sales       next_week 
1               1              10            20       
2               1              15             0 
1               2              20             0 

请您参考如下方法:

使用DataFrame.sort_values与 DataFrameGroupBy.shift :

#if not sure if sorted per 2 columns 
df = df.sort_values(['product','Week_Number']) 
 
#pandas 0.24+ 
df['next_week'] = df.groupby('product')['Sales'].shift(-1, fill_value=0) 
#pandas below 
#df['next_week'] = df.groupby('product')['Sales'].shift(-1).fillna(0, downcast='int') 
print (df) 
   product  Week_Number  Sales  next_week 
0        1            1     10         20 
1        2            1     15          0 
2        1            2     20          0 

如果可能重复并需要先在真实数据中聚合sum:

df = df.groupby(['product','Week_Number'], as_index=False)['Sales'].sum() 
df['next_week'] = df.groupby('product')['Sales'].shift(-1).fillna(0, downcast='int') 
print (df) 
   product  Week_Number  Sales  next_week 
0        1            1     10         20 
1        1            2     20          0 
2        2            1     15          0