【问题标题】:How to reshape data in pandas to plot with Choropleth如何重塑 pandas 中的数据以使用 Choropleth 进行绘图
【发布时间】:2018-07-07 07:10:30
【问题描述】:

我正在尝试使用 Choropleth 绘制一些数据(尤其是来自 GitHub (terrorism in EU countries) 的数据集。

我有这样的事情:

year  country1  countr2 country3
1970  10        20      30  
1971  40        50      60    
1972  70        80      90

据我所知,应该是这样的:

year  country   value
1970  country1  10
1970  country2  20
1970  country3  30
1971  country1  40
1971  country2  50
1971  country3  60
1972  country1  70
1972  country2  80
1972  country3  90

如何使用 Pandas 实现这一目标?这是解决问题的好方法吗?

非常感谢。

【问题讨论】:

    标签: python pandas dataframe reshape choropleth


    【解决方案1】:

    这种任务对 Pandas 来说简直是小菜一碟 :)

    你只需要stack你的DataFrame:

    >>> import pandas as pd
    >>> # First you need to make `iyear` as index when reading csv to DataFrame.
    >>> df = pd.read_csv('eu_terrorism_fatalities_by_country.csv', index_col=0)
    >>> df.iloc[0:5, 0:3] # Take a look
           Belgium  Denmark  France
    iyear                          
    1970         0        0       0
    1971         0        0       0
    1972         0        0       1
    1973         0        0       5
    1974         0        0       3
    >>> res = df.stack() # Just this simple :D
    >>> res.head() # That's it.
    iyear         
    1970   Belgium    0
           Denmark    0
           France     0
           Germany    0
           Greece     2
    dtype: int64
    

    注意结果res是一个MultiIndex Series,还有一些后续:

    >>> res.index.names = ['year', 'country']
    >>> res.name = 'value'
    >>> res.head()
    year  country
    1970  Belgium    0
          Denmark    0
          France     0
          Germany    0
          Greece     2
    Name: value, dtype: int64
    >>> res.to_csv('results.csv', header=True)
    

    results.csv 文件中:

    year,country,value
    1970,Belgium,0
    1970,Denmark,0
    1970,France,0
    ... ...
    2014,Portugal,0
    2014,Spain,0
    2014,United Kingdom,0
    

    跟进您的评论,如果您想将 MultiIndex Series res 转换为 DataFrame,只需 reset_index 并使用它的 args 控制行为:

    >>> flat = res.reset_index()
    >>> flat.head()
       year  country  value
    0  1970  Belgium      0
    1  1970  Denmark      0
    2  1970   France      0
    3  1970  Germany      0
    4  1970   Greece      2
    >>> flat2 = res.reset_index(level=1)
    >>> flat2.head()
          country  value
    year                
    1970  Belgium      0
    1970  Denmark      0
    1970   France      0
    1970  Germany      0
    1970   Greece      2
    

    【讨论】:

    • 感谢您的精彩解释!我设法找到了 stack() 方法,但正如你所说,它返回一个系列。按照您的指示,我可以编写生成的 CSV 文件,然后将其重新导入新的 DataFrame。但是我想知道有没有办法避免这一步,直接从堆积的数据中获取一个DataFrame。换句话说,如何将一个系列(其中每个元素代表 3 列)转换为 DataFrame?
    • @juancar 这也很简单:) 看看编辑后的答案。
    猜你喜欢
    • 2021-10-15
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 2017-05-29
    • 1970-01-01
    • 2020-10-21
    相关资源
    最近更新 更多