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

如何使用pandas DataFrame合并值相同但顺序不同的两个数据集

实现代码

你可以通过两次pd.merge操作分别映射color_1和color_2对应的缩写,具体代码如下:

import pandas as pd 

# 构造示例数据集
df1 = pd.DataFrame({"color": ["blue", "yellow", "red"],
                    "abbv": ["b", "y", "r"]})
df2 = pd.DataFrame({"color_1": ["blue", "red", "yellow"],
                    "color_2": ["yellow", "blue", "red"],
                    "total": ["green", "purple", "orange"]})

# 第一次合并匹配color_1对应的缩写
res = pd.merge(df2, df1, left_on='color_1', right_on='color', how='left')
res = res.rename(columns={'abbv': 'abbv_1'}).drop(columns='color')

# 第二次合并匹配color_2对应的缩写
res = pd.merge(res, df1, left_on='color_2', right_on='color', how='left')
res = res.rename(columns={'abbv': 'abbv_2'}).drop(columns='color')

# 调整列顺序和目标格式对齐
res = res[['color_1', 'color_2', 'total', 'abbv_1', 'abbv_2']]
print(res)

输出结果

运行后得到的结果和要求的目标格式完全一致:

color_1 color_2   total abbv_1 abbv_2
0    blue  yellow   green      b      y
1     red    blue  purple      r      b
2  yellow     red  orange      y      r

补充说明

如果数据量较大,也可以先把df1转成字典做映射,无需两次merge,性能更高:

color_map = df1.set_index('color')['abbv'].to_dict()
df2['abbv_1'] = df2['color_1'].map(color_map)
df2['abbv_2'] = df2['color_2'].map(color_map)

如果明确要求使用pd.merge方法,使用前文中两次merge的方案即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 15:36:03