【问题标题】:Groupby, Shift and Sum分组、移位和求和
【发布时间】:2019-07-09 08:48:59
【问题描述】:

我有以下数据框:

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

【问题讨论】:

    标签: python pandas shift


    【解决方案1】:

    DataFrame.sort_valuesDataFrameGroupBy.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
    

    【讨论】:

      【解决方案2】:

      先对数据进行排序
      然后使用转换应用移位

      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
      

      【讨论】:

        猜你喜欢
        • 2023-03-15
        • 1970-01-01
        • 2018-10-09
        • 1970-01-01
        • 2020-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多