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

Resample('W')异常结果:如何提取数据中每周最后存在的日期?

问题原因

resample('W')会将每个周的周期对齐到周日(默认的周结束日),因此即使原数据中该周的最后一个存在日期是周四,resample后的索引仍会被设置为当周的周日,导致day_name()显示周日,而非实际的最后存在日期的星期。

解决方案

我们需要按周分组后,保留原数据中每组最后一个存在日期的索引和对应值,而非使用resample的对齐日期。可以通过以下两种方式实现:

方法一:使用groupby+自定义分组提取

直接按周分组后,提取每组的最后一行数据,保留原日期索引:

import pandas as pd
import numpy as np

# 生成示例数据
date_list = ['2023-10-01', '2023-10-02', '2023-10-03', '2023-10-04', '2023-10-05']
date_rng = pd.to_datetime(date_list)
data = np.random.rand(len(date_rng))
time_series = pd.Series(data, index=date_rng)

# 按周分组,提取每组最后一行(保留原日期索引)
groups = time_series.groupby(pd.Grouper(freq='W'))
weekly_last = pd.Series(
    [group.iloc[-1] for _, group in groups if not group.empty],
    index=[group.index[-1] for _, group in groups if not group.empty]
)

# 添加星期列
weekly_last = weekly_last.to_frame('value')  # 转为DataFrame方便添加列
weekly_last['Day of the Week'] = weekly_last.index.day_name()

print(weekly_last)

方法二:使用groupby+agg聚合

通过聚合操作同时提取最后一个值和对应的原日期,再将日期设为索引:

import pandas as pd
import numpy as np

# 生成示例数据
date_list = ['2023-10-01', '2023-10-02', '2023-10-03', '2023-10-04', '2023-10-05']
date_rng = pd.to_datetime(date_list)
data = np.random.rand(len(date_rng))
time_series = pd.Series(data, index=date_rng)

# 按周聚合,提取最后一个值和对应日期
weekly_agg = time_series.groupby(pd.Grouper(freq='W')).agg(
    last_value=lambda x: x.iloc[-1],
    last_date=lambda x: x.index[-1]
).dropna()  # 过滤空周

# 设置原日期为索引,添加星期列
weekly_last = weekly_agg.set_index('last_date')
weekly_last['Day of the Week'] = weekly_last.index.day_name()

print(weekly_last)
输出结果

两种方法都会得到如下类似输出(值为随机数):

value Day of the Week
2023-10-01  0.123456789           Sunday
2023-10-05  0.987654321         Thursday

这样就实现了保留原数据中每周最后一个存在日期的需求,对应的星期也会正确显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 03:45:03