如何在 Python 数据框中添加包含字典字符串值的列

How to add a column with string values of a dictionary in Python dataframe

我正在尝试添加一个包含字典值的列。

DataFrame 如下所示,共有 29 个国家/地区 dataframe screenshot

我的词典如下所示:

# Define a dictionary containing european Regions 
eu_regions = {'Central and Eastern Europe': ['Latvia', 'Bulgaria', 'Lithuania', 'Croatia', 'Czechia','Poland','Romania', 'Slovakia', 'Slovenia', 'Hungary'],
        'Northern Europe': ['Sweden', 'Norway', 'Denmark', 'Finland', 'Estonia'],
        'Western Europe': ['Austria', 'Belgium', 'Luxembourg', 'Netherlands', 'France', 'Germany', 'Ireland', 'Norway', 'United Kingdom'],
        'Southern Europe': ['Italy', 'Cyprus','Malta', 'Portugal', 'Greece', 'Spain']}

要添加名为“region”的新列,这意味着添加我使用以下命令的每个国家/地区的区域。

eu_vaccine_df['region'] = eu_vaccine_df['country'].map(eu_regions)

eu_vaccine_df.head()

然而,在结果中,创建了新列“region”,但没有添加新的国家,因此无法将国家与字典中的地区相匹配。

这有帮助吗?

country_dct = {}
for key, countries in eu_regions.items():
    
    for country in countries:
        country_dct[country] = key


eu_vaccine_df['region'] = eu_vaccine_df['country'].map(country_dct)

eu_vaccine_df.head()