Groupby,移位和求和

时间:2019-07-09 08:48:59

标签: python pandas shift

我有以下数据框:

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

2 个答案:

答案 0 :(得分:1)

DataFrame.sort_valuesDataFrameGroupBy.shift结合使用:

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
   double c=106.895;
   cout<<fixed<<setprecision(9)<<std::scientific<<C<<endl;
   return 0;
}

如果可能重复,并且首先需要在真实数据中汇总#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

答案 1 :(得分:0)

首先对数据进行排序
然后使用tranform进行平移

df = pd.DataFrame(data={'product':[1,2,1],
                        'week_number':[1,1,2],
                        'sales':[10,15,20]})
df.sort_values(['product','week_number'],inplace=True)
df['next_week'] = df.groupby(['product'])['sales'].transform(pd.Series.shift,-1,fill_value=0)
print(df)
      product  week_number  sales  next_week
0        1            1     10         20
2        1            2     20          0
1        2            1     15          0