【问题标题】:Python Pandas, Matplotlib: Plot multi-index DataFrame possible?Python Pandas,Matplotlib:绘制多索引 DataFrame 可能吗?
【发布时间】:2018-09-07 08:27:36
【问题描述】:

这是我的df

                   User  Year Month Message
Date                
2017-07-21 07:55:39  Jw  2017   7   hey
2017-07-21 07:55:42  Jw  2017   7   bye bye
2017-07-21 07:55:48  Jw  2017   7   hi hi
2017-07-21 12:29:38  Jw  2017   7   Photo
2017-07-21 12:29:45  Jw  2017   7   abc

我将其按YearMonth 分组,并按count 汇总:

df[df['User']=='Jw'].groupby(['Year', 'Month']).agg({'Message':'count'})

结果:

              Message
Year    Month   
2017    7       193
        8       282
        9       86
        10      245
        11      42
        12      200
2018    1       302
        2       175
        3       65

我们将最终分组的数据框称为grouped_df

我想做的是绘制gourped_df,其中Year-Monthx-axisMessagey-axis

我认为有两种实现方式:

  1. 直接画图(我不知道怎么做,但我相信它存在)

  2. 删除Multiindex 并制作由Year-Month 组成的Date 列,并通过grouped_df[['Date', 'Message']] 过滤并绘制它。但是由于这个数据框是多索引结构,我不知道如何将这两个索引合并为一个日期列。

想知道这两种方法或更好的方法(如果存在)。

谢谢。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    有一种方法可以修复你的输出

    df.index=df.index.map('{0[0]}-{0[1]}'.format) 
    df
    Out[157]: 
             Message
    2017-7       193
    2017-8       282
    2017-9        86
    2017-10      245
    2017-11       42
    2017-12      200
    2018-1       302
    2018-2       175
    2018-3        65
    df.plot()
    

    或者我们只是从原来的df开始

    df.assign(key=df.Year.astype(str)+'-'df.Month.astype(str))[df['User']=='Jw'].groupby('key').agg({'Message':'count'})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-20
      • 2017-03-24
      • 2022-01-22
      • 2019-04-13
      • 2020-07-14
      • 2013-10-20
      • 1970-01-01
      • 2014-03-24
      相关资源
      最近更新 更多