猿问

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

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  


湖上湖
浏览 151回答 1
1回答

慕丝7291255

根据country_converter文档。to和参数的有效值src可以通过 找到coco.CountryConverter().valid_class。import country_converter as cocoimport pandas as pd# setupt test dataframedf = pd.DataFrame({'code': ['AFG', 'USA', 'RU']})# add country name by applying the convert methoddf['short name'] = df.code.apply(lambda x: coco.convert(names=x, to='name_short', not_found=None))# display(df)  code     short name0  AFG    Afghanistan1  USA  United States2   RU         Russia# converting the column to a list and passing it to the method also works to add the short namedf['short name'] = coco.convert(names=df.code.tolist(), to='name_short', not_found=None)
随时随地看视频慕课网APP

相关分类

Python
我要回答