我有下面的数据,其中有country wise orders data of ,持续2周。我想在按国家、和end_date分组的情况下,计算出与上周相比,食品订单的百分比变化(增减)。

Formula = (this_week_orders*100)/(last_week_orders) - 100
对于上面的df,我想得到最后的数据框架,如下所示
如我们所见,与上周相比,Russia had a decrease in order count of 33%和India had an increase of 50%

请建议如何编写自定义聚合函数,因为我只熟悉标准的sum()、count()等.
发布于 2020-10-08 17:09:37
df = pd.DataFrame({'start_date':['2020-09-21','2020-09-21','2020-09-28', '2020-09-28'],
'end_date':['2020-09-27', '2020-09-27', '2020-10-04', '2020-10-04'],
'Country':['Russia', 'India','Russia','India'],
'orders':[150,80,100,120]})
df['start_date'] = pd.to_datetime(df['start_date'])
df.sort_values(by='start_date', inplace=True)
df['% Change'] = df.groupby('Country')['orders'].pct_change()输出
start_date end_date Country orders % Change
0 2020-09-21 2020-09-27 Russia 150 NaN
1 2020-09-21 2020-09-27 India 80 NaN
2 2020-09-28 2020-10-04 Russia 100 -0.333333
3 2020-09-28 2020-10-04 India 120 0.500000https://stackoverflow.com/questions/64267198
复制相似问题