【问题标题】:Mapping a dictionary with Continent: Country to a DataFrame with a Country Column将带有 Continent: Country 的字典映射到带有 Country 列的 DataFrame
【发布时间】:2021-08-27 02:17:06
【问题描述】:

我有一个包含 df['Country'] 列的数据框。我创建了一个字典,其中所有大陆作为键,值作为相应国家/地区的列表。

continents = { "North America" : ["Canada","Mexico","United States"]}

我想将此映射到我的数据框,在其中创建一个列,其中包含 df['Country'] 对应大陆中的每个值。

我尝试了以下方法,但它返回一列 NA 值

df['Continents'] = df['Country'].map(continents)

我需要创建一个函数来绘制大陆地图还是可以使用 pandas 的 .map() 方法?

【问题讨论】:

  • 字典需要以另一种方式构建。 {'Canada': 'North America',... 键应该是列中的值

标签: python pandas dataframe


【解决方案1】:

您的字典格式错误,您需要相反的格式(并且没有列表)。

您可以使用它来获得正确的格式:

countries_map = {country: continent
                 for continent,countries in continents.items()
                 for country in countries}

输出:

{'Canada': 'North America',
 'Mexico': 'North America',
 'United States': 'North America'}

然后继续:

df['Continents'] = df['Country'].map(countries_map)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 2018-06-04
    • 2016-04-19
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    相关资源
    最近更新 更多