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

如何在Pandas中替换DataFrame中的指定缩写词汇?

Pandas DataFrame批量替换城市名称缩写

原始数据

我们有如下Pandas DataFrame:

import pandas as pd

city = pd.DataFrame({'id': [1,2,3,4],
                     'city': ['NRTH CAROLINA','NEW WST AMSTERDAM','EAST TOKYO','LONDON STH']})

需求

需要将city列中的缩写批量替换为完整拼写:

  • NRTH → NORTH
  • WST → WEST
  • STH → SOUTH

解决方案

使用str.replace()方法结合正则匹配,实现精准批量替换(\b用于匹配独立单词边界,避免误替换包含缩写字符的其他单词):

# 定义替换规则字典
replace_rules = {
    r'\bNRTH\b': 'NORTH',
    r'\bWST\b': 'WEST',
    r'\bSTH\b': 'SOUTH'
}

# 对city列执行替换
city['city'] = city['city'].str.replace(replace_rules, regex=True)

最终结果

执行后得到的DataFrame如下:

id   city
1    NORTH CAROLINA
2    NEW WEST AMSTERDAM
3    EAST TOKYO
4    LONDON SOUTH

简化写法(若缩写均为独立单词)

如果可以确定所有待替换的缩写都是独立的单词,也可以用更简洁的方式:

city['city'] = city['city'].replace({'NRTH': 'NORTH', 'WST': 'WEST', 'STH': 'SOUTH'}, regex=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:01:10