在 pandas 中按周分组 [英] group by week in pandas

查看:66
本文介绍了在 pandas 中按周分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数据框:

Name   Date    Quantity
Apple  07/11/17  20
orange 07/14/17  20
Apple  07/14/17  70
Orange 07/25/17  40
Apple  07/20/17  30

我想按名称和日期汇总以获取数量总和详情:

I want to aggregate this by Name and Date to get sum of quantities Details:

Date:分组,结果应该是在一周的开始(或就在星期一)

Date: Group, the result should be at the beginning of the week (or just on Monday)

数量:总和,如果两个或多个记录具有相同的名称和日期(如果属于相同的间隔)

Quantity: Sum, if two or more record have same Name and Date(if falls on same interval)

所需的输出如下:

Name   Date    Quantity
Apple  07/10/17  90
orange 07/10/17  20
Apple  07/17/17  30
orange 07/24/17  40

提前致谢

推荐答案

First convert column date to_datetime 并减去一周,因为我们要对日期前一周而不是该日期前一周求和.

First convert column date to_datetime and substract one week, as we want to sum for the week ahead of the date, not the week before that date.

然后使用 groupbyGrouperW-MON 和聚合sum:

df['Date'] = pd.to_datetime(df['Date']) - pd.to_timedelta(7, unit='d')
df = df.groupby(['Name', pd.Grouper(key='Date', freq='W-MON')])['Quantity']
       .sum()
       .reset_index()
       .sort_values('Date')
print (df)
     Name       Date  Quantity
0   Apple 2017-07-10        90
3  orange 2017-07-10        20
1   Apple 2017-07-17        30
2  Orange 2017-07-24        40

这篇关于在 pandas 中按周分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆