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

Python DataFrame实操:如何映射两个DataFrame并获取匹配列名

双DataFrame行业分类映射方案

实现逻辑

  • 先统一两个表中行业字段的大小写格式,避免大小写不一致导致匹配失败
  • 遍历df2生成「行业名称: 对应值为1的列名」的映射字典
  • 通过map方法将映射规则应用到df1的Sector列,快速生成匹配结果

完整代码

import pandas as pd

# 统一df2的Name列首字母大写,和df1的Sector格式对齐,解决大小写不匹配问题
df2['Name'] = df2['Name'].str.capitalize()

# 构建映射字典
sector_category_map = {}
for _, row in df2.iterrows():
    # 提取当前行值为1的列名
    target_col = row[row == 1].index[0]
    sector_category_map[row['Name']] = target_col

# 映射到df1生成新列
df1['Matched_Category'] = df1['Sector'].map(sector_category_map)

运行结果

执行后df1的输出如下:

Name       Sector Matched_Category
0  Company1           3D    Manufacturing
1  Company2   Accounting          Finance
2  Company3     Wireless    Entertainment

多匹配场景适配

如果df2某行存在多个值为1的列,可调整代码返回列表格式的匹配结果:

sector_category_map = {}
for _, row in df2.iterrows():
    target_cols = row[row == 1].index.tolist()
    sector_category_map[row['Name']] = target_cols

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 12:06:03