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

Pandas中如何用另一DataFrame的国名替换目标DataFrame中的编码

替换DataFrame文本中的国家编码为对应国名

你遇到的问题是:df1的Countries description列里嵌入了国家编码(比如C0001),需要用df2里的编码-国名映射把这些编码替换成实际国名,但用merge方法没成功。

原始数据

df1

Countries descriptionContinentsvalues
C0001 also called America,America21tr
C0004 and C0003 are neighbhorsEurope504 bn
on advancing C0005 with C0001.securityEurope600bn
C0002, the smallest continentAustrali1.7tr

df2(编码-国名映射)

CountriesId
USC0001
AustraliaC0002
FinlandC0003
NorwayC0004
JapanC0005

为什么merge没用?

你之前试的df1.merge(df2, on=['Countries'], how='left')肯定不行,因为merge是基于整列匹配来合并DataFrame的,而你的编码是藏在Countries description的文本里,不是单独的列,merge根本找不到匹配的列,自然没法替换文本内容。

正确解决方案

我们需要把编码映射转成字典,再用正则批量替换文本里的编码:

完整代码

import pandas as pd
import re

# 构造示例df1
df1 = pd.DataFrame({
    'Countries description': [
        'C0001 also called America,',
        'C0004 and C0003    are neighbhors',
        'on advancing C0005 with C0001.security',
        'C0002, the smallest continent'
    ],
    'Continents': ['America', 'Europe', 'Europe', 'Australi'],
    'values': ['21tr', '504 bn', '600bn', '1.7tr']
})

# 构造示例df2
df2 = pd.DataFrame({
    'Countries': ['US', 'Australia', 'Finland', 'Norway', 'Japan'],
    'Id': ['C0001', 'C0002', 'C0003', 'C0004', 'C0005']
})

# 1. 将df2转为编码到国名的字典
code_map = df2.set_index('Id')['Countries'].to_dict()

# 2. 用正则匹配所有编码并替换
def replace_code(match):
    code = match.group(0)
    return code_map.get(code, code)  # 如果找不到编码,保留原内容

df1['Countries description'] = df1['Countries description'].replace(
    r'\bC\d{4}\b',  # 匹配C开头+4位数字的编码,\b确保是完整编码
    replace_code,
    regex=True
)

print(df1)

替换后结果

Countries descriptionContinentsvalues
US also called America,America21tr
Norway and Finland are neighbhorsEurope504 bn
on advancing Japan with US.securityEurope600bn
Australia, the smallest continentAustrali1.7tr

代码说明

  • code_map把df2转成以编码为键、国名为值的字典,查询效率高;
  • 正则r'\bC\d{4}\b'精准匹配格式为C+4位数字的编码,避免误匹配类似C0001abc这种带后缀的字符串;
  • replace方法结合自定义函数,把每个匹配到的编码替换成对应的国名,找不到的编码会保留原样(避免报错)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:21:01