Pandas 按日期小时匹配另一数据集为DataFrame新增关联列
实现步骤
核心思路是将两个表的时间字段统一对齐到小时整点维度,再通过关联匹配得到对应天气数据,完整可运行代码如下:
import pandas as pd # 示例数据(你已有的可跳过这部分) data = pd.DataFrame({'date':['1/01/2001 0:20:15', '1/1/2001 1:10:55', '1/1/2001 2:05:31'], 'location':[('x1','y1'),('x2','y2'),('x3','y3')]}) weather = pd.DataFrame({'date':['1/01/2001 0:00:00','1/01/2001 1:00','1/01/2001 2:00'], 'condition':['snow','light snow','rain']}) # 1. 统一转换日期格式,生成小时维度的匹配键 data['date'] = pd.to_datetime(data['date']) data['hour_match_key'] = data['date'].dt.floor('H') # 时间向下取整到小时 weather['date'] = pd.to_datetime(weather['date']) weather['hour_match_key'] = weather['date'].dt.floor('H') # 2. 左连接匹配天气,删除辅助匹配列 data = data.merge( weather[['hour_match_key', 'condition']], on='hour_match_key', how='left' ).drop('hour_match_key', axis=1)
运行结果
最终得到的data表如下:
| date | location | condition |
|---|---|---|
| 2001-01-01 00:20:15 | (x1, y1) | snow |
| 2001-01-01 01:10:55 | (x2, y2) | light snow |
| 2001-01-01 02:05:31 | (x3, y3) | rain |
注意事项
- 若存在某条数据的小时维度在
weather表中无对应记录,匹配后condition列会返回NaN,你可以根据需求用fillna()方法自定义缺失值填充规则 - 如果你的数据量很大,可以提前删除
weather表中多余字段再做关联,提升运行效率
内容的提问来源于stack exchange,提问作者Lee
相关产品推荐
相关产品推荐

