gpt4 book ai didi

python - 如何在pandas中使用country_converter将国家/地区代码转换为名称

转载 作者:行者123 更新时间:2023-12-02 02:37:50 24 4
gpt4 key购买 nike

df
Date Value CODE
0 2020-03-12 7 AFG
1 2020-03-11 7 AFG
...

如何从代码生成国家/地区?我尝试了从 CODE 变量生成代码

import country_converter as coco
df['country'] = df['CODE'].apply(coco.convert)
Actual Output:
Date Value CODE country
0 2020-03-12 7 AFG AFG
1 2020-03-11 7 AFG AFG
Expected Output:
Date Value CODE country
0 2020-03-12 7 AFG Afghanistan
1 2020-03-11 7 AFG Afghanistan

最佳答案

  • 根据 country_converter文档。
  • 可以通过 coco.CountryConverter().valid_class 找到 tosrc 参数的有效值。
import country_converter as coco
import pandas as pd

# setupt test dataframe
df = pd.DataFrame({'code': ['AFG', 'USA', 'RU']})

# add country name by applying the convert method
df['short name'] = df.code.apply(lambda x: coco.convert(names=x, to='name_short', not_found=None))

# display(df)
code short name
0 AFG Afghanistan
1 USA United States
2 RU Russia

# converting the column to a list and passing it to the method also works to add the short name
df['short name'] = coco.convert(names=df.code.tolist(), to='name_short', not_found=None)

关于python - 如何在pandas中使用country_converter将国家/地区代码转换为名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64051741/

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