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

如何基于多列匹配项在两个DataFrame之间复制值?

多条件匹配合并DataFrame列

我有两个DataFrame(df1和df2),数据结构如下:

df1
index   gameID  Team        A      B      C
0       0001    Lakers      10     100    90
1       0001    Clippers    20     105    91
2       0002    Celtics     30     110    92
3       0002    Warriors    40     115    93
4       0003    Suns        10     100    94
5       0003    Jazz        20     105    95
6       0004    Heat        30     110    96
7       0004    Magic       40     115    97
df2
index   gameID  Team        Player      D
0       0001    Lakers      Lebron      30.5
1       0001    Clippers    Harden      29.9
2       0002    Celtics     Tatum       31.2 
3       0002    Warriors    Curry       29.8    
4       0003    Suns        Durant      40.6    
5       0003    Jazz        Clarkson    21.5    
6       0004    Heat        Butler      25.5    
7       0004    Magic       Banchero    27.8
8       0005    Mavs        Doncic      39.9
9       0005    Raptors     Quickley    19.6

我需要将df1中的A、B、C列复制到df2中,仅当gameID和Team列同时匹配时才完成复制,不匹配的行对应列填充NaN,预期结果如下:

df2
index   gameID  Team        Player      D        A     B     C
0       0001    Lakers      Lebron      30.5     10    100   90
1       0001    Clippers    Harden      29.9     20    105   91
2       0002    Celtics     Tatum       31.2     30    110   92
3       0002    Warriors    Curry       29.8     40    115   93
4       0003    Suns        Durant      40.6     10    100   94
5       0003    Jazz        Clarkson    21.5     20    105   95
6       0004    Heat        Butler      25.5     30    110   96
7       0004    Magic       Banchero    27.8     40    115   97
8       0005    Mavs        Doncic      39.9     NaN   NaN   NaN
9       0005    Raptors     Quickley    19.6     NaN   NaN   NaN

我曾尝试使用dict结合map方法,但该方法仅支持单键值对,无法满足多列条件的需求。


解决方案

使用pandas的merge方法,通过多列(gameID和Team)作为匹配键,采用左连接(how='left')即可实现需求,保留df2的所有行,匹配到的行填充A、B、C列的值,未匹配的则填充NaN。

具体代码如下:

import pandas as pd

# 假设df1和df2已创建完成
result_df = pd.merge(df2, df1[['gameID', 'Team', 'A', 'B', 'C']], 
                     on=['gameID', 'Team'], 
                     how='left')

# 若需保留df2原索引,可添加left_index=True参数
# result_df = pd.merge(df2, df1[['gameID', 'Team', 'A', 'B', 'C']], 
#                      on=['gameID', 'Team'], 
#                      how='left',
#                      left_index=True)

关键说明

  • on=['gameID', 'Team']:指定同时用这两列作为匹配的判断依据
  • how='left':以df2为基准保留所有行,未匹配到的列自动填充NaN
  • 仅选择df1中需要的列进行合并,避免引入多余数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 07:54:51