首页 > 解决方案 > 如何在熊猫中进行此操作

问题描述

我有一个包含国家列的数据框。不幸的是,国家名称字符都是大写的,我需要它们是 ISO3166_1_Alpha_3
例如美国将是美国英国将是英国等等。

幸运的是,我在互联网上找到了这个数据框,其中包含 2 个重要列,第一个是国家名称,第二个是 ISO3166_1_Alpha_3 你可以在这个网站上找到这个数据框 https://datahub.io/JohnSnowLabs/iso-3166-country -codes-itu-dialing-codes-iso-4217-currency-codes

所以我写了这段代码

data_geo = pd.read_excel("tab0.xlsx")#this is the data frame that contains all the capitalized country name
country_iso = pd.read_csv(r"https://datahub.io/JohnSnowLabs/iso-3166-country-codes-itu-dialing-codes-iso-4217-currency-codes/r/iso-3166-country-codes-itu-dialing-codes-iso-4217-currency-codes-csv.csv",
                          usecols=['Official_Name_English', 'ISO3166_1_Alpha_3'])

s = pd.Series(data_geo.countery_name_e).str.lower().str.title()#this line make all the names characters small except the first character
y = pd.Series([])

现在我想在一个循环

s = Official_Name_English 

我想追加

country_iso[Official_Name_English].ISO3166_1_Alpha_3

Y系列。如果国家/地区名称不在此列表中,则附加NaN 这是 s 中的 20 行

['Diffrent Countries', 'Germany', 'Other Countries', 'Syria',
       'Jordan', 'Yemen', 'Sudan', 'Somalia', 'Australia',
       'Other Countries', 'Syria', 'Lebanon', 'Jordan', 'Yemen', 'Qatar',
       'Sudan', 'Ethiopia', 'Djibouti', 'Somalia', 'Botswana Land']

你知道我怎么做这个吗?

标签: pandasdataframeseries

解决方案


你可以试试map

data_geo = pd.read_excel("tab0.xlsx")
country_iso = pd.read_csv(r"https://datahub.io/JohnSnowLabs/iso-3166-country-codes-itu-dialing-codes-iso-4217-currency-codes/r/iso-3166-country-codes-itu-dialing-codes-iso-4217-currency-codes-csv.csv",
                      usecols=['Official_Name_English', 'ISO3166_1_Alpha_3'])
s = pd.Series(data_geo.countery_name_e).str.lower().str.title()

mapper = (country_iso.drop_duplicates('Official_Name_English')
                     .dropna(subset=['Official_Name_English'])
                     .set_index('Official_Name_English')['ISO3166_1_Alpha_3'])
y = data_geo['countery_name_e'].map(mapper)

推荐阅读