从 pandas 中的子组获取统计信息

Get statistics from subgroups in pandas

我有这个数据框,其中过滤了 df['two']=0 的数据,然后我将它分组为连续 "subgroups",在 "results" 中显示答案。

import pandas as pd
import numpy as np
import itertools
import operator

index = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p']
df  = pd.DataFrame(index=index)
df['one']  = range(16)
df['two'] = [-1,0,0,-1,1,0,0,-1,-1,0,0,0,0,0,-1,1]
df['three'] =  [0,1,3,5,5,8,10,12,13,17,18,20,22,24,25,26]

df_filter = df[((df['two']==0))]
df_filter_list = df_filter.one.tolist()

results = []
for k, g in itertools.groupby(enumerate(df_filter_list), lambda (i,x):i-x):
        group = map(operator.itemgetter(1), g)
        results.append(group)

print results 
[[1, 2], [5, 6], [9, 10, 11, 12, 13]]

现在我的问题是,如何使用 "results" 的值并返回获取特定列的每个不同子组的统计信息?

例如,如果我想知道第二个 "sub group"(结果中的 [5,6])的 df['three'] 的平均值,它将是第 5 个和列 'three' 的第 6 行,因此是 5 和 8 的平均值。 或者,如果我想知道第三个 "subgroup" [9,10,11,12,13] 的最大值,那就是 26。

如果您必须保留 "results" 中的原始值,您可以使用另一个列表来 "shift" 索引(results[1] 中的值 1 用于 [5,6] 的第一个示例]):

results2=[]
for item in results[1]:
    results2.append(item -1)

然后得到你的子集:

sub = df.iloc[results2]

并计算平均值:

sub['three'].mean()

实际上只是稍微调整一下您的答案并了解您是如何使用 iloc 的,这正是我所需要的。发布它以防对某人有用:

与其这样做,还不如得到第 1 组的统计数据:

results2=[]
for item in results[1]:
    results2.append(item -1)
sub = df.iloc[results2]
sub['three'].mean()

我刚刚做了这个,这会给你每个子组的平均值(或你需要的任何东西)。

for z in range(len(results)):
    sub =  df.iloc[results[z]]
    print sub['three'].mean()