熊猫:从字典中替换完整匹配字符串

时间:2017-07-28 09:54:07

标签: python regex pandas dictionary

我使用字典替换数据框中的一些条目:

dict1 = {
    "Republic of Korea": "South Korea",
    "United States of America": "United States",
    "United Kingdom of Great Britain and Northern Ireland": "United Kingdom",
    "China, Hong Kong Special Administrative Region": "Hong Kong"
}

使用df.replace()几乎可以完成工作:

energy['Country'] = energy['Country'].replace(dict1, regex=True)

但是,我意识到该函数正在替换每个字符串匹配,我想将替换函数限制为完整字符串匹配,因为我得到了不需要的替换,如:

"Democratic People's Republic of Korea" miss-cleaned as "Democratic People's South Korea"

我已经尝试在字典中使用正则表达式,但似乎无法正常工作。

有什么想法吗?提前谢谢。

1 个答案:

答案 0 :(得分:3)

删除regex=True以指定完全替换。

相关问题