计算每月熊猫的分类数据

时间:2017-09-05 09:36:37

标签: python pandas matplotlib dataframe seaborn

我正在尝试计算分类数据并绘制每个月的高,中,低的百分比。

它应该如下图所示:

enter image description here

我有一个日期和分数的数据框,如下所示

-------------------------------
|Date                 | Score  |
|2016-1-02 00:00:00   | High   |
|2016-2-02 00:00:00   | Low    |
|2016-4-23 00:00:00   | Med    |
|2016-5-03 00:00:00   | High   |
|2016-6-02 00:00:00   | High   |
|2016-6-04 00:00:00   | Low    |
|2016-7-02 00:00:00   | Med    |
|2016-12-02 00:00:00  | High   |
-------------------------------

我知道我可以这样做以获得每一个的分割,但我不知道如何按月拆分,然后计算每个

 df.groupby('Score').size()

 Score:
 High: 5
 Med: 15
 Low: 155

谢谢

1 个答案:

答案 0 :(得分:5)

首先准备数据

In [2056]: dff = (df.set_index('Date').groupby('Score')
                    .resample('MS').count().unstack('Score'))

In [2057]: dff
Out[2057]:
           Score
Score       High  Low  Med
Date
2016-01-01   1.0  NaN  NaN
2016-02-01   0.0  1.0  NaN
2016-03-01   0.0  0.0  NaN
2016-04-01   0.0  0.0  1.0
2016-05-01   1.0  0.0  0.0
2016-06-01   1.0  1.0  0.0
2016-07-01   0.0  NaN  1.0
2016-08-01   0.0  NaN  NaN
2016-09-01   0.0  NaN  NaN
2016-10-01   0.0  NaN  NaN
2016-11-01   0.0  NaN  NaN
2016-12-01   1.0  NaN  NaN

标准化百分比。

In [2058]: dff.div(dff.sum(1), axis=0).plot.bar(stacked=True)
Out[2058]: <matplotlib.axes._subplots.AxesSubplot at 0x1386ca58>

enter image description here

相关问题