2 回答

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
首先,您應(yīng)該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貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
考慮到您有數(shù)據(jù)集,或者您可以通過 pycountry,您可以使用以下方法進(jìn)行處理。
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
現(xiàn)在,考慮到您對長度為 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
添加回答
舉報(bào)