【问题标题】:How to add a column with string values of a dictionary in Python dataframe如何在Python数据框中添加带有字典字符串值的列
【发布时间】:2021-06-11 07:16:07
【问题描述】:

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

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']}

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

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

eu_vaccine_df.head()

然而,在结果中,新列“region”被创建,但没有添加新的国家,并且无法将国家与字典的区域匹配。

【问题讨论】:

    标签: python dataframe dictionary kaggle


    【解决方案1】:

    这有帮助吗?

    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()
    

    【讨论】:

    • 你是真正的英雄!是的,它奏效了。谢谢卢卡斯 :)
    • 太好了,我能帮忙:)
    猜你喜欢
    • 1970-01-01
    • 2020-12-04
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    相关资源
    最近更新 更多