【问题标题】:How do I access a pandas groupby dataframe by grouped index?如何通过分组索引访问 pandas groupby 数据框?
【发布时间】:2018-12-09 23:31:57
【问题描述】:

按照this example我可以创建一个简单的数据框和groupby

import pandas as pd

# Create a sample data frame
df = pd.DataFrame({'A': ['foo', 'foo', 'foo', 'bar', 'bar'],
                   'B': range(5), 'C': range(5)})

# group by 'A' and sum 'B'
gf = df.groupby('A').agg({'B': 'sum'})

结果是分组的数据帧 gf

    B
A   
bar 7
foo 3

我想通过分组索引访问 gf。比如……

gf['foo'] returns 3 
gf['bar'] returns 7

我还想按分组索引进行绘图。比如……

gf.plot('A', 'B') such that  x=['foo','bar'], y=[3,7]

【问题讨论】:

    标签: python python-3.x pandas pandas-groupby


    【解决方案1】:

    怎么样:

    import matplotlib.pyplot as plt
    
    for k in gf['B'].index:
        print "{}: {}".format(k, gf['B'].loc[k])
    
    plt.bar(gf['B'].index, map(lambda i: gf['B'].loc[i], gf['B'].index))
    plt.show()
    

    【讨论】:

      【解决方案2】:
      gf.reset_index(level=0, inplace=True)
      
      gf[gf.A == 'bar']
      

      返回:

           A  B
      0  bar  7
      

      剧情:

      import matplotlib.pyplot as plt
      
      plt.bar(gf.A, gf.B)
      

      【讨论】:

        猜你喜欢
        • 2019-01-07
        • 1970-01-01
        • 2013-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-27
        • 2016-09-28
        相关资源
        最近更新 更多