首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用grouper从确切日期开始按周进行聚合

使用grouper从确切日期开始按周进行聚合
EN

Stack Overflow用户
提问于 2021-12-02 23:59:25
回答 2查看 44关注 0票数 0

我想使用pandas grouper聚合我的周数据,其中一周在我上次约会的同一天结束,而不是一周的结束。

这是我写的代码:

代码语言:javascript
复制
fp.groupby(pd.Grouper(key='date',freq='w')).collectionName.nunique().tail(10)

结果如下:

代码语言:javascript
复制
date
2021-10-03     644
2021-10-10     698
2021-10-17     756
2021-10-24     839
2021-10-31     883
2021-11-07     905
2021-11-14     961
2021-11-21    1028
2021-11-28     990
2021-12-05     726
Freq: W-SUN, Name: collectionName, dtype: int64

我拥有的最后一个日期是2021-12-02,所以我希望它是一周聚合的最后一天,它每7天返回一次,直到结束(在本例中是数据集的开始)。

我需要你的帮助。

EN

回答 2

Stack Overflow用户

发布于 2021-12-03 00:08:28

pd.DataFrame.resamplerule='1w'on='date'origin='end_day'一起使用

票数 0
EN

Stack Overflow用户

发布于 2021-12-03 03:34:52

这假设您可以找到分组之前的最后一个日期。请在此处查看参考资料:https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases和此处:https://www.programiz.com/python-programming/datetime/strftime

代码语言:javascript
复制
df = pd.DataFrame({'date': pd.date_range(start='2021-01-01 01:04:16', periods=250), 'val':range(1,251)})

                   date  val
0   2021-01-01 01:04:16    1
1   2021-01-02 01:04:16    2
2   2021-01-03 01:04:16    3
3   2021-01-04 01:04:16    4
4   2021-01-05 01:04:16    5
..                  ...  ...
245 2021-09-03 01:04:16  246
246 2021-09-04 01:04:16  247
247 2021-09-05 01:04:16  248
248 2021-09-06 01:04:16  249
249 2021-09-07 01:04:16  250

[250 rows x 2 columns]

# locate last date and get day of week in correct format
anchor = df['date'].iat[-1].strftime("%a")

df.groupby(pd.Grouper(key='date',freq='w-' + anchor)).nunique().tail(5)

# week ends on the same day as the original dataset
            val
date
2021-08-10    7
2021-08-17    7
2021-08-24    7
2021-08-31    7
2021-09-07    7
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70207936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档