如何通过字典匹配替换Pandas DataFrame中的文本值?
解决方法
先重现你的数据和字典:
import pandas as pd # 构建原始DataFrame df = pd.DataFrame({ 'text': ['Aztecs', 'Apple', 'Mayans', 'Christopher', 'Banana', 'Martin'] }) # 给定的映射字典 d = {1023: ['Aztecs', 'Mayans'], 2213: ['Apple','Banana'], 3346: ['Christopher', 'Martin']}
步骤1:反转字典,生成值到键的映射
原字典是键→多个值的结构,我们需要转换成单个值→对应键的映射,用字典推导式快速实现:
reverse_map = {val: key for key, vals in d.items() for val in vals}
生成的reverse_map结构为:
{'Aztecs': 1023, 'Mayans': 1023, 'Apple': 2213, 'Banana': 2213, 'Christopher': 3346, 'Martin': 3346}
步骤2:替换DataFrame中的值
用Pandas的map()方法直接替换text列的内容:
df['text'] = df['text'].map(reverse_map)
最终结果
执行后你的DataFrame会变成:
| text |
|---|
| 1023 |
| 2213 |
| 1023 |
| 3346 |
| 2213 |
| 3346 |
可选:处理不存在的映射值
如果text列中有不在字典里的内容,map()会返回NaN,可以用fillna()填充默认值:
df['text'] = df['text'].map(reverse_map).fillna('未匹配')
内容的提问来源于stack exchange,提问作者LVA
相关产品推荐
相关产品推荐

