【问题标题】:How to plot yearly dataset using pandas?如何使用熊猫绘制年度数据集?
【发布时间】:2017-11-16 01:59:34
【问题描述】:

我想绘制 {a, b} 对的年使用量折线图。

X 轴应该是年份,y 轴应该是使用量。

这是我的数据集。

a   b       year    usage   
a2  10104   2011    7.292787
a0  10104   2012    43.545533
b0  12011   2009    96.130359
b1  12011   2009    7.658487
b1  14102   2010    6.975572

【问题讨论】:

    标签: pandas matplotlib time-series


    【解决方案1】:

    如果a, b vs year 没有重复则使用:

    s = df.set_index(['year','a','b'])['usage']
          .unstack([1,2])
          .sort_‌​index(axis=1)
          .interpolate('index')
    s.index = s.index.astype(str)
    s.plot()
    

    【讨论】:

    • 但是,有很多 {a, b} 对。我不应该申请 groupby 什么的吗?
    • 是的,当然,但是你需要用年数计算对数吗?喜欢df.groupby('year')['a','b'].size().plot()
    【解决方案2】:

    使用pivot_table 重新排列数据,以便我在列中有ab 的组合,在索引中有year

    但是,一旦我们进行了透视,可能会丢失数据。通过使用interpolateindex 参数,我们用插值填充缺失数据,同时保持与索引值的相对变化成比例。这在索引值没有统一分隔时很重要,例如[2005, 2006, 2008]。如果索引是统一分隔的,那么使用index 不会有坏处,因为它与默认值相同。

    d1 = df.pivot_table('usage', 'year', ['a', 'b']).interpolate('index')
    d1.index = pd.PeriodIndex(d1.index, freq='A')
    d1.plot()
    


    对@jezrael 的 cmets 的回应

    观察没有interpolate的数据是什么样子是有益的

    d1 = df.pivot_table('usage', 'year', ['a', 'b'])
    d1.index = pd.PeriodIndex(d1.index, freq='A')
    d1
    
    a            a0        a2         b0        b1          
    b         10104     10104      12011     12011     14102
    year                                                    
    2009        NaN       NaN  96.130359  7.658487       NaN
    2010        NaN       NaN        NaN       NaN  6.975572
    2011        NaN  7.292787        NaN       NaN       NaN
    2012  43.545533       NaN        NaN       NaN       NaN
    

    在这种情况下,我们看不到会发生什么。但我想象有更多的数据,我们会看到稀疏数据之间的NaN 差距。代替前向填充,我们可以按比例填充。

    d1 = df.pivot_table('usage', 'year', ['a', 'b']).interpolate('index')
    d1.index = pd.PeriodIndex(d1.index, freq='A')
    d1
    
    a            a0        a2         b0        b1          
    b         10104     10104      12011     12011     14102
    year                                                    
    2009        NaN       NaN  96.130359  7.658487       NaN
    2010        NaN       NaN  96.130359  7.658487  6.975572
    2011        NaN  7.292787  96.130359  7.658487  6.975572
    2012  43.545533  7.292787  96.130359  7.658487  6.975572
    

    再一次,这只会在更多数据的情况下显示出它的好处。与这些数据一样,我们只能观察到有限的前向填充。


    关于mean
    请注意,我使用pivot_table 并且pivot_table 句柄之一是index/column 规范中是否存在重复项。它将使用aggfunc 聚合落入该单元格的所有值。默认情况下,该函数为mean。但是,在这种情况下,根据已提供的数据,没有重复的 a/b/year 组合。因此,没有发生聚合。

    【讨论】:

    • 太棒了!但我的 x 轴(年份)显示“0.0 0.5 1.0 ... +2.009e3”。如何将其更改为显示年份?
    • 谢谢。你保存我的数据!
    • @jezrael 感谢您鼓励我 :-)
    猜你喜欢
    • 2017-05-28
    • 1970-01-01
    • 2020-05-31
    • 2022-11-15
    • 2018-02-10
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多