gpt4 book ai didi

python - 在一行代码中用 pandas 执行多个替换

转载 作者:太空宇宙 更新时间:2023-11-04 09:38:03 25 4
gpt4 key购买 nike

我想按如下方式更改我的数据:

"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"

目前,我正在使用代码:

energy.Country[energy.Country == "Republic of Korea"] = "South Korea"
energy.Country[energy.Country == "United States of America"] = "United States"
energy.Country[energy.Country == "United
Kingdom of Great Britain and Northern Ireland"] = "United Kingdom"
energy.Country[energy.Country == "China,
Hong Kong Special Administrative Region"] ="Hong Kong"`

我尝试使用 .replace 方法来做同样的事情,将参数作为字典传递:

energy.replace('国家' : {"大韩民国": "韩国",
"United States of America": "美利坚合众国",
"United Kingdom of Great Britain and Northern Ireland": "联合王国",
"中国香港特别行政区": "香港"})

但是好像不行,有没有更干净整洁的方法呢?

最佳答案

Series 上调用 replace,这更容易。

repl_dict = {"Republic of Korea": "South Korea", ...}
energy['Country'] = energy['Country'].replace(repl_dict)

请注意,这不是使用 map 的好地方,因为“Country”中没有映射到 repl_dict 中任何内容的条目将被替换为 NaN。


另一种选择是基于 list-comp 的替换:

energy['Country'] = [
repl_dict.get(x, x) for x in energy['Country'].tolist()]

不像replace那样简洁,但在性能方面绝对非常称职。

关于python - 在一行代码中用 pandas 执行多个替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52918274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com