2 回答
TA贡献1883条经验 获得超3个赞
首先,您应该pycountry通过pip install pycountry在命令提示符下键入并按来安装软件包enter。
import pycountry
import pycountry
df = pd.DataFrame({"country_code": ['AF', 'BEL', 'AUS', 'DE', 'IND', 'US', 'GBR','XYZ'],
"amount": [100, 200, 140, 400, 225, 125, 600,0]})
list_alpha_2 = [i.alpha_2 for i in list(pycountry.countries)]
list_alpha_3 = [i.alpha_3 for i in list(pycountry.countries)]
def country_flag(df):
if (len(df['country_code'])==2 and df['country_code'] in list_alpha_2):
return pycountry.countries.get(alpha_2=df['country_code']).name
elif (len(df['country_code'])==3 and df['country_code'] in list_alpha_3):
return pycountry.countries.get(alpha_3=df['country_code']).name
else:
return 'Invalid Code'
df['country_name']=df.apply(country_flag, axis = 1)
df
amount country_code country_name
0 100 AF Afghanistan
1 200 BEL Belgium
2 140 AUS Australia
3 400 DE Germany
4 225 IND India
5 125 US United States
6 600 GBR United Kingdom
7 0 XYZ Invalid Code
TA贡献1860条经验 获得超8个赞
考虑到您有数据集,或者您可以通过 pycountry,您可以使用以下方法进行处理。
import pycountry
new_df = df['country-code'].apply(lambda x: pycountry.countries.get(alpha_3=x).name if len(x) == 3 else pycountry.countries.get(alpha_2=x).name)
print new_df
这打印:
new_df
0 Afghanistan
1 Belgium
2 Australia
3 Germany
4 India
5 United States
6 United Kingdom
Name: country_code, dtype: object
现在,考虑到您对长度为 2 和长度为 3 的代码都有 csv,如下所示:
df2
code name
0 AF Afghanistan
1 DE Germany
2 US United States
和
df3
code name
0 BEL Belgium
1 AUS Australia
2 IND India
3 GBR United Kingdom
在此之后,您可以按照以下步骤操作:
>>> new_df2 = df.merge(df2, left_on='country_code', right_on='code')
>>> new_df2
amount country_code code name
0 100 AF AF Afghanistan
1 400 DE DE Germany
2 125 US US United States
>>> new_df3 = df.merge(df3, left_on='country_code', right_on='code')
>>> new_df3
amount country_code code name
0 200 BEL BEL Belgium
1 140 AUS AUS Australia
2 225 IND IND India
3 600 GBR GBR United Kingdom
>>> df23 = pd.concat([new_df2, new_df3])
>>> df23.reset_index(inplace=True)
>>> df23.drop('index', inplace=True, axis=1)
>>> df23
amount country_code code name
0 100 AF AF Afghanistan
1 400 DE DE Germany
2 125 US US United States
3 200 BEL BEL Belgium
4 140 AUS AUS Australia
5 225 IND IND India
6 600 GBR GBR United Kingdom
添加回答
举报