You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中定义可配置的周起始频率?

Pandas自定义周起始频率的分组问题

我需要在Pandas中定义一个可配置周起始日的频率,目标是将某一周内的所有日期都归类到该周的起始日下。例如,2025-01-06(周一)至2025-01-13(周日)的所有日期,都应该被分组到2025-01-06这个起始日。但使用Pandas的DateOffset时,日期会被向前滚动到下一周期,导致分组结果不符合预期。

示例代码及当前问题:

import pandas as pd

range_dex = pd.date_range(start="2025-01-06", end="2025-01-30")
sample_series = pd.Series(1, index=range_dex)
sample_series
# 输出:
# 2025-01-06    1
# 2025-01-07    1
# 2025-01-08    1
# ...
# 2025-01-28    1
# 2025-01-29    1
# 2025-01-30    1
# Freq: D, dtype: int64

week_start = 0  # 0代表周一,...,6代表周日
freq_pd = pd.offsets.Week(n=1, weekday=week_start)

sample_series.groupby(pd.Grouper(freq=freq_pd)).size()
# 当前输出:
# 2025-01-06    1
# 2025-01-13    7
# 2025-01-20    7
# 2025-01-27    7
# 2025-02-03    3
# Freq: W-MON, dtype: int64

期望得到的分组结果:

sample_series.groupby(pd.Grouper(freq=freq_pd)).size()
# 期望输出:
# 2025-01-06    7
# 2025-01-13    7
# 2025-01-20    7
# 2025-01-27    4
# Freq: W-MON, dtype: int64

我尝试过pd.offsets.Week(n=0, weekday=week_start)和pd.offsets.Week(n=-1, weekday=week_start),但均报错。也无法通过Series运算调整,且需要支持.asfreq方法,希望能通过频率参数解决该问题。

附2025年1月日历:

SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
2627282930311

内容的提问来源于stack exchange,提问作者bhub

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 22:32:42