如何基于最近时间点匹配两个pandas DataFrame以合并气象温度与负荷数据
你可以直接使用pandas内置的merge_asof方法实现需求,核心是设置direction='nearest'参数匹配时间差绝对值最小的记录,操作步骤如下:
1. 预处理校验
首先确保两个DataFrame的时间索引为datetime类型,且按时间升序排序(merge_asof要求输入必须按匹配的时间字段有序):
import pandas as pd # 索引转datetime格式,避免字符串索引导致匹配错误 dfweather.index = pd.to_datetime(dfweather.index) dfload.index = pd.to_datetime(dfload.index) # 按时间索引升序排序 dfweather = dfweather.sort_index() dfload = dfload.sort_index()
2. 执行最近时间匹配
以dfload为左表,匹配dfweather的temp字段:
df_merged = pd.merge_asof( left=dfload, right=dfweather[["temp"]], # 仅取需要的temp字段,避免其他列冲突 left_index=True, right_index=True, direction="nearest" # 核心参数:匹配时间差最小的记录,不限制前后 )
3. 可选增强配置
- 如果你有多个气象站点需要分别匹配,可以加
by="station"参数(前提是dfload中也有station字段) - 如果你需要限制最大匹配时间差,避免过远的时间匹配到错误数据,可以加
tolerance参数:
# 示例:仅匹配前后30分钟以内的气象数据,超过时间差的temp返回空值 df_merged = pd.merge_asof( left=dfload, right=dfweather[["temp"]], left_index=True, right_index=True, direction="nearest", tolerance=pd.Timedelta(minutes=30) )
按你给出的示例数据执行后,2017-01-01 00:20的dfload记录会正确匹配到最近的2017-01-01 00:52对应的temp值45.00,完全符合你的需求。
内容的提问来源于stack exchange,提问作者mathcomp guy
相关产品推荐
相关产品推荐

