仅显示已定义组的Pandas groupby结果

时间:2015-07-09 09:49:25

标签: python pandas group-by python-3.4

我有一个以下基本格式的pandas数据框:

tempDF = pd.DataFrame({ 'id': [12,12,12,12,45,45,45,51,51,51,51,51,51,76,76,76,91,91,91,91],
                        'measure': [3.2,4.2,6.8,5.6,3.1,4.8,8.8,3.0,1.9,2.1,2.4,3.5,4.2,5.2,4.3,3.6,5.2,7.1,6.5,7.3],
                        'status': [0,1,1,2,1,1,0,1,0,1,2,0,0,1,1,0,1,0,2,2]})

我希望根据“度量”中的值获取每个“状态”的摘要统计信息。为此,我使用:

tempGroup = tempDF.groupby('status')
tempGroup['measure'].describe()

...并且“状态”中的每个组都必须生成一系列摘要统计信息。但是,在我的实际数据库中,类别的数量要大得多,对于某些分析,我只想显示有限数量类别的结果。在上面的示例中,如何仅显示状态组1和2的摘要统计信息?我尝试过使用.loc和其他标准方法进行切片和切块的各种形式,但无济于事。我已经能够使用for循环单独逐步遍历每个组,但这看起来非常低效 - 我假设必须有一个更简单的方法。 任何帮助将不胜感激。提前谢谢。

2 个答案:

答案 0 :(得分:1)

使用groups属性获取群组,然后使用get_group并为该群组调用describe

In [189]:
tempGroup.groups

Out[189]:
{0: [0, 6, 8, 11, 12, 15, 17],
 1: [1, 2, 4, 5, 7, 9, 13, 14, 16],
 2: [3, 10, 18, 19]}

In [188]:
tempGroup.get_group(0)['measure'].describe()

Out[188]:
count    7.000000
mean     4.614286
std      2.432714
min      1.900000
25%      3.350000
50%      3.600000
75%      5.650000
max      8.800000
Name: measure, dtype: float64

这些组只是来自groups的键:

In [190]:
tempGroup.groups.keys()

Out[190]:
dict_keys([0, 1, 2])

答案 1 :(得分:1)

如果您只想要状态1和2的统计信息。

import pandas as pd
import numpy as np


tempDF = pd.DataFrame({ 'id': [12,12,12,12,45,45,45,51,51,51,51,51,51,76,76,76,91,91,91,91],
                        'measure': [3.2,4.2,6.8,5.6,3.1,4.8,8.8,3.0,1.9,2.1,2.4,3.5,4.2,5.2,4.3,3.6,5.2,7.1,6.5,7.3],
                        'status': [0,1,1,2,1,1,0,1,0,1,2,0,0,1,1,0,1,0,2,2]})

# just show stats for 1, 2
groups = [1, 2]
tempDF.loc[tempDF.status.isin(groups)].groupby('status').describe()


Out[41]: 
                   id  measure
status                        
1      count   9.0000   9.0000
       mean   51.0000   4.3000
       std    27.3038   1.4186
       min    12.0000   2.1000
       25%    45.0000   3.1000
       50%    51.0000   4.3000
       75%    76.0000   5.2000
       max    91.0000   6.8000
2      count   4.0000   4.0000
       mean   61.2500   5.4500
       std    37.8627   2.1486
       min    12.0000   2.4000
       25%    41.2500   4.8000
       50%    71.0000   6.0500
       75%    91.0000   6.7000
       max    91.0000   7.3000