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
相关产品推荐
相关产品推荐

