Pandas Merge合并DataFrame时modelvals列出现nan值如何解决
问题修复方案
从给出的合并结果可以看出,business_name、maint_region_name、dataset等DF2的列都有正常取值,仅modelvals列为空,说明合并键的匹配逻辑是生效的,问题并非出在合并匹配环节,可按以下优先级排查修复:
- 排查DF2对应匹配行的
modelvals原始值
先取DF1的单行合并键,去DF2中精准过滤查看对应值,确认是否为原始数据本身存在空值:
# 取DF1第一行的合并键做测试 test_plant = DF1.loc[0, "plant_name"] test_year = DF1.loc[0, "year"] test_month = DF1.loc[0, "month"] test_day = DF1.loc[0, "day"] test_hour = DF1.loc[0, "hour"] # 查看DF2中对应行的modelvals值 print(DF2[(DF2["plant_name"] == test_plant) & (DF2["year"] == test_year) & (DF2["month"] == test_month) & (DF2["day"] == test_day) & (DF2["hour"] == test_hour)]["modelvals"])
如果输出结果本身包含NaN,说明是DF2原始数据中同一合并键下存在空值行,合并时对齐到了空值行,可先对DF2做聚合预处理再合并:
# 按合并键分组,保留各字段的第一个非空值,也可根据需求替换为max/mean等聚合逻辑 DF2_agg = DF2.groupby(["plant_name", "year", "month", "day", "hour"], as_index=False).agg( business_name = ("business_name", "first"), maint_region_name = ("maint_region_name", "first"), modelvals = ("modelvals", lambda x: x.dropna().iloc[0] if len(x.dropna())>0 else None), dataset = ("dataset", "first") ) # 用聚合后的DF2做合并 DF3 = DF1.merge(DF2_agg, on=["plant_name", "year", "month", "day", "hour"], how="inner")
- 处理字符串合并键的隐形字符问题
object类型的plant_name列很可能存在前后空格、不可见控制字符等肉眼无法识别的差异,可作为备选排查项:
# 清理两个表的plant_name字段的首尾空白、多余空格 DF1["plant_name"] = DF1["plant_name"].str.strip().str.replace(r"\s+", " ", regex=True) DF2["plant_name"] = DF2["plant_name"].str.strip().str.replace(r"\s+", " ", regex=True)
- 排查DF2的副本视图问题
如果DF2是其他DataFrame切片生成的视图,可能存在取值异常,合并前先做一次深拷贝即可:
DF3 = DF1.merge(DF2.copy(deep=True), on=["plant_name", "year", "month", "day", "hour"], how="inner")
内容的提问来源于stack exchange,提问作者user2100039
相关产品推荐
相关产品推荐

