仅显示定义组的 Pandas groupby 结果

Display Pandas groupby results for defined groups only

我有一个具有以下基本格式的 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]})

我想根据 'measure' 中的值获取每个 'status' 的汇总统计信息。为此,我使用:

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

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

对该组使用 groups attribute to get the groups and then use get_group and call 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 和 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