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

Excel表格DataFrame重采样时时间起始偏移问题求助

问题解决:跨天时间序列的重采样异常

问题根源

你的时间数据是跨天序列(从当日22:47:52到次日3:51:30),但使用pd.to_datetime解析时,所有时间默认被归到同一天(1900-01-01),导致时间索引顺序混乱(次日的00:00~03:51会被排在当日22:47之前)。resample会以索引中的最小时间为基准生成序列,最终出现从00:00:00开始的错误结果。

解决方案

需要先修正跨天时间的日期归属,确保索引是按时间递增的正确序列,再进行重采样。

步骤1:读取并修正跨天时间索引

import pandas as pd

# 读取Excel数据
df = pd.read_excel(R"C:\Users\XXX.xlsx", sheet_name="XXX", usecols=[0, 1], index_col=[0], skiprows=[0, 1])

# 先将索引转为时间对象(仅保留时分秒)
df.index = pd.to_datetime(df.index, format='%H:%M:%S').time

# 处理跨天逻辑:当当前时间小于前一个时间时,视为次日
prev_time = None
current_date = pd.Timestamp('1900-01-01')
corrected_dates = []

for t in df.index:
    if prev_time is not None and t < prev_time:
        current_date += pd.Timedelta(days=1)
    corrected_dates.append(pd.Timestamp.combine(current_date, t))
    prev_time = t

# 替换索引为带正确日期的时间序列,并排序
df.index = pd.DatetimeIndex(corrected_dates)
df = df.sort_index()

步骤2:从指定时间开始重采样

# 定义目标起始时间
target_start = pd.Timestamp('1900-01-01 22:48:00')

# 筛选起始时间之后的数据,再以1秒间隔重采样
df_filtered = df.loc[target_start:]
df_upsampled = df_filtered.resample('1s').asfreq()

# 查看结果
print(df_upsampled)

补充说明

  • 如果需要填充缺失的体温值(比如线性插值),可以将asfreq()替换为interpolate(method='linear'),这样重采样后的NaN会被插值填充。
  • 修正后的索引包含正确的日期信息,resample会自动识别连续的时间范围,不会再出现从00:00:00开始的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 13:17:36