Pandas中如何用另一DataFrame的国名替换目标DataFrame中的编码
替换DataFrame文本中的国家编码为对应国名
你遇到的问题是:df1的Countries description列里嵌入了国家编码(比如C0001),需要用df2里的编码-国名映射把这些编码替换成实际国名,但用merge方法没成功。
原始数据
df1
| Countries description | Continents | values |
|---|---|---|
| C0001 also called America, | America | 21tr |
| C0004 and C0003 are neighbhors | Europe | 504 bn |
| on advancing C0005 with C0001.security | Europe | 600bn |
| C0002, the smallest continent | Australi | 1.7tr |
df2(编码-国名映射)
| Countries | Id |
|---|---|
| US | C0001 |
| Australia | C0002 |
| Finland | C0003 |
| Norway | C0004 |
| Japan | C0005 |
为什么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 description | Continents | values |
|---|---|---|
| US also called America, | America | 21tr |
| Norway and Finland are neighbhors | Europe | 504 bn |
| on advancing Japan with US.security | Europe | 600bn |
| Australia, the smallest continent | Australi | 1.7tr |
代码说明
code_map把df2转成以编码为键、国名为值的字典,查询效率高;- 正则
r'\bC\d{4}\b'精准匹配格式为C+4位数字的编码,避免误匹配类似C0001abc这种带后缀的字符串; replace方法结合自定义函数,把每个匹配到的编码替换成对应的国名,找不到的编码会保留原样(避免报错)。
内容的提问来源于stack exchange,提问作者Shaikh Shoeb
相关产品推荐
相关产品推荐

