【问题标题】:Map keys to values in pandas Python将键映射到熊猫 Python 中的值
【发布时间】:2021-03-01 03:09:06
【问题描述】:

我有这本从 Wikipedia 上刮下来的字典。该词典包含各大洲及其各自的国家。例如:

theWorld = {'Asia': ['China', 'Malaysia'.. etc], 'Europe': ['Germany', 'Italy' ..etc]}

我正在尝试使用 pandas 制作一个数据框,以将一个国家/地区映射到其大陆。例如:

Country   Continent
China     Asia
Malaysia  Asia 
Germany   Europe
Ghana     Africa

等等等等。

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    您可以使用 list comprehension 创建 DataFrame 的行:

    import pandas as pd
    
    theWorld = {'Asia': ['China', 'Malaysia'], 'Europe': ['Germany', 'Italy']}
    
    df = pd.DataFrame(data=[[v, k] for k, vs in theWorld.items() for v in vs], columns=['country', 'continent'])
    print(df)
    

    输出

        country continent
    0     China      Asia
    1  Malaysia      Asia
    2   Germany    Europe
    3     Italy    Europe
    

    其他资源:

    • DataFrame数据结构,here
    • 何时使用列表解析,here

    【讨论】:

    • 谢谢,这解决了我的问题。您能否告诉我应该为您提供的解决方案寻找什么样的参考资料。
    • 我还不懂列表理解,但我转换为正常循环,我有点明白你做了什么,所以再次感谢你。 data= [] for k, vs in theWorld.items(): for v in vs: data.append([v,k]) print(data)
    • @Ozeus 我将一些资源链接到列表理解,希望对您有所帮助
    • 真的很有帮助。谢谢。
    【解决方案2】:

    您可以分两步完成,首先在字典理解中反转字典,然后使用该国家/地区映射创建数据框:

    >>> import pandas as pd
    >>> the_world = {
    ...         'Asia': ['China', 'Malaysia'],
    ...         'Europe': ['Germany'],
    ...         'Africa': ['Ghana']
    ...     }
    >>> country_to_continent = {
    ...         country: continent
    ...         for continent, countries in the_world.items() 
    ...         for country in countries
    ...     }
    >>> country_to_continent
    {'China': 'Asia', 'Malaysia': 'Asia', 'Germany': 'Europe', 'Ghana': 'Africa'}
    >>> df = pd.DataFrame(
    ...         data={
    ...             'Country': country_to_continent.keys(),
    ...             'Continent': country_to_continent.values()
    ...         })
    >>> df
        Country Continent
    0     China      Asia
    1  Malaysia      Asia
    2   Germany    Europe
    3     Ghana    Africa
    

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 2018-02-08
      • 2019-01-02
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 2021-05-03
      • 1970-01-01
      相关资源
      最近更新 更多