【发布时间】:2017-07-24 21:06:27
【问题描述】:
我有一个包含各种列的数据框,并希望在每个组具有最少数量的有效成员的条件下计算组的平均值。我使用 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 尝试这个时,我的大脑被扭曲了。
【问题讨论】:
-
回答你的小问题:
df.loc[df['x'] < -0.6, 'x'] = np.nan -
我很想说
df.filter(...).groupby('id').mean()是获得您想要的东西的最有效方式。