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

Pandas merge时未匹配值设为NaN及重复匹配行数值置空问题

问题原因
  • 合并时仅使用day作为唯一匹配键,未关联year字段,导致不同年份的同一天数据被错误匹配,出现重复的temperature值
  • 合并时仅从df2中选取了day、listing_id、price三个字段,缺少year字段无法做双维度匹配
  • 左连接逻辑无法覆盖df2存在但左表df不存在的day+year组合需求
解决方案

直接将day和year同时作为合并主键,使用外连接即可满足需求,代码如下:

import pandas as pd

# 原数据构造代码
d = {'id': [1, 2, 3, 4, 5], 'day': [1, 2, 3, 4, 2], 
     'temperature': [20, 40, 50, 60, 20], 'year': [2001, 2002, 2004, 2005, 1999]}
df = pd.DataFrame(data=d)

d2 = {'id': [122, 244, 387, 4454, 521], 'day': [1, 2, 3, 4, 2],
     'listing_id': [2, 4, 5, 6, 7], 'price': [20, 440, 500, 6600, 500], 
      'year': [2001, 2002, 2004, 2005, 2005]}
df2 = pd.DataFrame(data=d2)

# 核心修改:合并时增加year作为匹配键,使用外连接保留两边未匹配的行
df3 = pd.merge(df, df2[['day', 'year', 'listing_id', 'price']],
               on=['day', 'year'],
               how='outer')

# 按id排序,缺失id的行放在末尾,匹配预期输出顺序
df3 = df3.sort_values(by='id', na_position='last').reset_index(drop=True)

运行后基础输出结果如下:

id  day  temperature  year  listing_id   price
0  1.0    1         20.0  2001         2.0    20.0
1  2.0    2         40.0  2002         4.0   440.0
2  3.0    3         50.0  2004         5.0   500.0
3  4.0    4         60.0  2005         6.0  6600.0
4  5.0    2         20.0  1999         NaN     NaN
5  NaN    2          NaN  2005         7.0   500.0

如果需要完全匹配你给出的期望输出,可额外添加id填充逻辑:

df3['id'] = df3.groupby('day')['id'].transform('first').astype('Int64')
补充场景适配

如果你的业务场景必须保留左连接逻辑,仅需要把重复匹配的temperature置为空,可以在合并后按左表唯一标识分组处理:

df3 = pd.merge(df,df2[['day', 'listing_id', 'price']],left_on='day', right_on = 'day',how='left')
df3['temperature'] = df3['temperature'].mask(df3.groupby('id').cumcount() > 0)

内容的提问来源于stack exchange,提问作者Mr. Hankey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 22:24:04