python – pandas groupby:有效的条件聚合?

我有一个包含各种列的数据框,并希望在每个组具有最小有效成员数的条件下计算组的平均值.我使用groupby,filter和mean尝试了以下内容.它似乎有效,但我想知道是否有更有效的解决方案?

import pandas as pd
import numpy as np

df = pd.DataFrame({'id' : ['one', 'one', 'two', 'three', 'two',
                           'two', 'two', 'one', 'three', 'one'],
                   'idprop' : [1., 1., 2., 3., 2.,   # property corresponding to id
                               2., 2., 1., 3., 1.],
                    'x' : np.random.randn(10),
                    'y' : np.random.randn(10)})

# set a couple of x values to nan
s = df['x'].values
s[s < -0.6] = np.nan
df['x'] = s

g = df.groupby('id', sort=False)
# filter out small group(s) with less than 3 valid values in x
# result is a new dataframe
dff = g.filter(lambda d: d['x'].count() >= 3)

# this means we must group again to obtain the mean value of each filtered group
result = dff.groupby('id').mean()
print result
print type(result)

然而,在how to get multiple conditional operations after a Pandas groupby?处存在相关问题,其仅按行值“过滤”而不是按组元素的数量.转换为我的代码,这将是:

res2 = g.agg({'x': lambda d: df.loc[d.index, 'x'][d >= -0.6].sum()})

作为一个侧面问题:是否有更有效的方法将值设置为低于或高于给定阈值NaN?当我用loc尝试这个时,我的大脑扭曲了.

最佳答案 您可以使用groupby
apply功能实现此目的:

def mean_cond(dfg):
    if dfg['x'].count() >= 3:
        return dfg.mean()
    return None

print df.groupby('id').apply(mean_cond).dropna()

这里的优点是分组过程只执行一次,这可能比在过滤器之后运行另一个groupby更有效.也许唯一的问题是,这会导致不符合条件的组在结果表中显示为NaN.通过最后添加dropna命令可以轻松解决这个问题.

点赞