为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

湖上湖 2023-09-05 17:21:37
df         Date        Value CODE0      2020-03-12      7  AFG1      2020-03-11      7  AFG...我如何从代码生成国家/地区?我尝试从 CODE 变量生成代码import country_converter as cocodf['country'] = df['CODE'].apply(coco.convert)Actual Output:         Date        Value CODE  country0      2020-03-12      7  AFG     AFG  1      2020-03-11      7  AFG     AFG Expected Output:         Date        Value CODE  country0      2020-03-12      7  AFG     Afghanistan  1      2020-03-11      7  AFG     Afghanistan  
查看完整描述

1 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞

  • 根据country_converter文档。

  • to和参数的有效值src可以通过 找到coco.CountryConverter().valid_class

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)



查看完整回答
反对 回复 2023-09-05
  • 1 回答
  • 0 关注
  • 93 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信