简体   繁体   English

迭代地绘制来自熊猫数据框的值

[英]Iteratively plot values from a pandas dataframe

I have a pandas dataframe, the result of a groupby() operation, c : 我有一个pandas数据框,是groupby()操作c

>>> c.index.names
FrozenList([u'Thing1', u'Thing2', u'Month'])
>>> c.columns
Index([u'Tot'], dtype='object')
>>> c
                           Tot
Thing1 Thing2 Month                
G      P      2012-12-01   0.017640
              2013-01-01   0.012062
              2013-02-01   0.029022
              2013-03-01   0.007593
              2013-04-01   0.004862
              2013-05-01   0.002671
              2013-06-01   0.014895
              2013-07-01   0.029641
              2013-08-01   0.051129
              2013-09-01   0.023913
              2013-10-01   0.061406
              2013-11-01   0.054781
              2014-01-01   0.017115
              2014-02-01   0.011919
H      K      2013-06-01   2.390632
              2013-07-01   7.066034
              2013-08-01   5.426312
              2013-09-01   8.276066
              2013-10-01   5.745811
              2013-11-01   2.250162
              2013-12-01   0.976822
              2014-01-01   1.438316
              2014-02-01   3.507220
       M      2012-06-01   3.050136
              2012-07-01   5.911788
              2012-08-01   2.794381
              2012-09-01   4.418268
              2012-10-01   5.312635
              2012-11-01   1.810977
              2012-12-01   3.097878
              2013-01-01   0.811326
              2013-02-01   3.105154
              2013-03-01   2.384704

I can plot a graph for a particular pair of Thing1 and Thing2 eg G and P like so: 我可以绘制一对Thing1Thing2的图形,例如GP如下所示:

c.loc[('G', 'P'), :].plot(kind='bar')

However I'd like to iterate through the DataFrame and plot separate graphs for all combinations of Thing1 and Thing2 . 但是,我想遍历DataFrame并为Thing1Thing2所有组合绘制单独的图。 I have tried using index.get_level_values however this results in combinations that do not exist eg G and M and therefore produces an error: 我尝试使用index.get_level_values但是这会导致不存在例如GM组合,因此会产生错误:

for x in c.index.get_level_values(0).unique():
    for y in c.index.get_level_values(1).unique():
        c.loc[(x, y), :].plot(kind='bar')

Does anyone know how to best do this? 有谁知道如何做到最好?

Do this 做这个

c.groupby(level=['Thing1', 'Thing2']).plot(kind='bar')

This will give you len(df.index.levels[0]) * len(df.index.levels[1]) plots. 这将为您提供len(df.index.levels[0]) * len(df.index.levels[1])绘图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM