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

如何根据df1 Airplanes的分隔符,将df2的Description匹配合并到df1?

问题描述

我有如下两个Pandas DataFrame:

import pandas as pd

df1 = pd.DataFrame({'Airplanes' : ['U-2','B-52,P-51', 'F-16', 'MiG-21,F-16;A-10', 'P-51','A-10;P-51' ],
                    'Company' : ['Air_1', 'Air_3', 'Air_2','Air_1', 'Air_7', 'Air_3']})

df1输出:

Airplanes Company
0               U-2   Air_1
1         B-52,P-51   Air_3
2              F-16   Air_2
3  MiG-21,F-16;A-10   Air_1
4              P-51   Air_7
5         A-10;P-51   Air_3
df2 = pd.DataFrame({'Model' : ['U-2','B-52', 'F-16', 'MiG-21', 'P-51','A-10' ],
                    'Description' : ['Strong', 'Huge', 'Quick','Light', 'Silent', 'Comfortable']})

df2输出:

Model  Description
0     U-2       Strong
1    B-52         Huge
2    F-16        Quick
3  MiG-21        Light
4    P-51       Silent
5    A-10  Comfortable

需求:将df2中的信息整合到df1中,新增Description列,且该列需与df1的Airplanes列保持完全一致的分隔符格式,最终输出如下:

Airplanes Company                 Description
0               U-2   Air_1                       Strong
1         B-52,P-51   Air_3                 Huge,Silent
2              F-16   Air_2                       Quick
3  MiG-21,F-16;A-10   Air_1     Light,Quick;Comfortable
4              P-51   Air_7                      Silent
5         A-10;P-51   Air_3          Comfortable;Silent
解决方案

核心思路是先建立型号与描述的快速映射,再按原字符串的分隔层级(分号→逗号)拆分、替换、拼接,完整保留原格式。

实现代码:

import pandas as pd

# 构建原始DataFrame
df1 = pd.DataFrame({'Airplanes' : ['U-2','B-52,P-51', 'F-16', 'MiG-21,F-16;A-10', 'P-51','A-10;P-51' ],
                    'Company' : ['Air_1', 'Air_3', 'Air_2','Air_1', 'Air_7', 'Air_3']})
df2 = pd.DataFrame({'Model' : ['U-2','B-52', 'F-16', 'MiG-21', 'P-51','A-10' ],
                    'Description' : ['Strong', 'Huge', 'Quick','Light', 'Silent', 'Comfortable']})

# 生成型号到描述的映射字典,提升查找效率
model_desc_map = df2.set_index('Model')['Description'].to_dict()

# 定义替换函数:严格保留原分隔符格式
def map_airplane_to_desc(airplane_str):
    # 先按分号拆分外层分组
    outer_parts = airplane_str.split(';')
    processed_outer = []
    for part in outer_parts:
        # 再按逗号拆分内层型号
        inner_models = part.split(',')
        # 替换每个型号为对应描述
        inner_descs = [model_desc_map[model] for model in inner_models]
        # 用逗号拼接内层结果
        processed_outer.append(','.join(inner_descs))
    # 用分号拼接外层结果
    return ';'.join(processed_outer)

# 应用函数生成新列
df1['Description'] = df1['Airplanes'].apply(map_airplane_to_desc)

# 打印结果
print(df1)

代码说明:

  1. 用model_desc_map字典存储型号与描述的对应关系,避免重复查询DataFrame,提升处理速度;
  2. map_airplane_to_desc函数分层处理分隔符:先处理分号分隔的大组,再处理每组内的逗号分型号,替换后按原分隔符拼接,完美保留原格式;
  3. 通过apply将函数批量应用到Airplanes列的每一行,生成目标Description列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:05:25