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

Python中如何重采样时间序列至整点并保留原数据?

如何在Pandas中将时间重采样至整点并保留原数据

问题背景

用户有一份包含风向(wd)和风速(ws)的CSV文件,内容如下:

datetime  wd  ws
06.02.2023 00:55  297  3.2
06.02.2023 01:55  296  2.7
06.02.2023 02:55  299  3.0
06.02.2023 03:55  302  3.5

期望将每条数据的时间重采样至下一个整点,同时保留原wd和ws数据,输出效果如下:

datetime  wd  ws
06.02.2023 01:00  297  3.2
06.02.2023 02:00  296  2.7
06.02.2023 03:00  299  3.0
06.02.2023 04:00  302  3.5

用户尝试的脚本及错误输出:

import pandas as pd
filename = r"data.csv"
df = pd.read_csv(filename, header=None, sep=";", skiprows=1, usecols = [0,3,4], names = ["datetime","wd","ws"])

# 指定日期格式
df['index_time']= pd.to_datetime(df['local_time'], format='%d.%m.%Y %H:%M')

# 将日期时间列设为索引
df.set_index('index_time', inplace=True)

# 尝试重采样
df_resampled = df.resample(rule='H')

执行print(df_resampled)后得到全NaN的错误输出:

local_time     wd   ws
index_time                                       
2023-02-06 00:00:00               NaN    NaN  NaN
2023-02-06 01:00:00               NaN    NaN  NaN
2023-02-06 02:00:00               NaN    NaN  NaN
2023-02-06 03:00:00               NaN    NaN  NaN

问题分析

你的代码存在两个核心问题:

  1. 列名匹配错误:读取CSV时指定了names=["datetime","wd","ws"],但后续却调用了不存在的local_time列,导致时间索引全为NaN,重采样自然无有效数据。
  2. 方法使用错误:resample是用于时间序列聚合的工具,而你的需求只是调整时间戳到下一个整点,不需要聚合操作,用resample完全没必要。

正确实现代码

import pandas as pd

# 读取CSV:sep=r"\s+"适配空格分隔,header=0指定第一行为表头
df = pd.read_csv("data.csv", header=0, sep=r"\s+", names=["datetime", "wd", "ws"])

# 将datetime列转为Pandas时间格式
df["datetime"] = pd.to_datetime(df["datetime"], format="%d.%m.%Y %H:%M")

# 将时间向上取整到下一个整点
df["datetime"] = df["datetime"].dt.ceil("H")

# 输出结果
print(df)

执行后会得到符合预期的输出:

datetime   wd   ws
0 2023-02-06 01:00:00  297  3.2
1 2023-02-06 02:00:00  296  2.7
2 2023-02-06 03:00:00  299  3.0
3 2023-02-06 04:00:00  302  3.5

补充说明

  • 如果需要保留原始时间列,仅新增重采样后的列,可以修改为:
    df["resampled_datetime"] = df["datetime"].dt.ceil("H")
    
  • 若后续需要对整点数据做聚合(比如求每小时平均风速),再使用resample,但当前需求用dt.ceil是最直接高效的方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 00:00:55