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

如何在Pandas中按日重采样后提取每周周一(周初)数据

问题:提取按日插值后每周周一的数据

我有月度数据,用Pandas执行按日重采样并三次插值后,能通过is_month_end属性提取月末数据,代码如下:

import pandas as pd
df=pd.read_excel(input_file, sheet_name='mthly', usecols='A:D', na_values='ND', index_col=0, header=0)
df.index.names = ['Period']
df.index = pd.to_datetime(df.index)

q= pd.Series(df[series], index=df.index)
d = q.resample('D').interpolate(method='cubic')  
m=d[d.index.is_month_end]

但我需要提取每周周一的数据,找不到对应属性或函数,该怎么解决?

数据示例

  • 输入月度数据
Period  Values
Jan-22  1
Feb-22  3
Mar-22  7
Apr-22  5
May-22  4
  • 按日重采样并三次插值后的结果
Period
2022-01-01    1.000000
2022-01-02    0.884487
2022-01-03    0.785650
2022-01-04    0.703004
2022-01-05    0.636066
2022-01-06    0.584353
2022-01-07    0.547382
2022-01-08    0.524668
2022-01-09    0.515729
2022-01-10    0.520081
2022-01-11    0.537240
2022-01-12    0.566724
2022-01-13    0.608048
and so on
  • 期望输出:每周周一的数据
2022-01-03    0.785650
2022-01-10    0.520081
and so on

解决方法

可以利用Pandas中DatetimeIndex的weekday属性筛选周一数据:

  • Pandas默认将周一对应weekday=0,周二到周日依次为1-6,直接判断索引的weekday是否等于0即可。

修改后的代码如下:

import pandas as pd
df=pd.read_excel(input_file, sheet_name='mthly', usecols='A:D', na_values='ND', index_col=0, header=0)
df.index.names = ['Period']
df.index = pd.to_datetime(df.index)

q= pd.Series(df[series], index=df.index)
d = q.resample('D').interpolate(method='cubic')  
# 提取每周周一的数据
mon_data = d[d.index.weekday == 0]

如果需要验证日期对应的星期,可使用day_name()辅助查看:

# 查看前10天的星期名称
print(d.index[:10].day_name())

运行后即可得到符合预期的每周周一数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 03:55:16