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

如何忽略年份基于DateTimeIndex合并两个Pandas DataFrame

实现方法

核心思路是提取两个数据集的月、日、小时作为公共匹配键,完成跨年份的关联合并,具体实现代码如下:

import pandas as pd

# 1. 重命名字段避免合并冲突
A = A.rename(columns={"Value": "ValueA"})
B = B.rename(columns={"Value": "ValueB"})

# 2. 为两个数据集添加共有的匹配维度(月、日、小时)
A["month"] = A.index.month
A["day"] = A.index.day
A["hour"] = A.index.hour

B["month"] = B.index.month
B["day"] = B.index.day
B["hour"] = B.index.hour

# 3. 左连接合并,保留A的全部时序数据
result = pd.merge(A, B, on=["month", "day", "hour"], how="left")

# 4. 删除辅助匹配列,得到最终结果
result = result.drop(columns=["month", "day", "hour"])

注意事项

如果数据集A包含闰年2月29日的测量数据,而作为基准的B数据集是平年数据无对应匹配项,合并后对应行的ValueB会出现空值,可根据业务需求用fillna()填充数值,或提前过滤掉A中2月29日的无效行即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 22:00:04