【问题标题】:pandas groupby: efficient conditional aggregation?pandas groupby:高效的条件聚合?
【发布时间】: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'] &lt; -0.6, 'x'] = np.nan
  • 我很想说df.filter(...).groupby('id').mean() 是获得您想要的东西的最有效方式。

标签: python pandas aggregate


【解决方案1】:

您可以使用 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 命令来解决。

【讨论】:

    猜你喜欢
    • 2019-08-10
    • 2018-09-29
    • 1970-01-01
    • 2021-12-17
    • 2019-03-10
    • 2014-11-23
    • 2018-02-03
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多