可以将 pandas GroupBy 函数作为参数传递给 python 函数吗?我应该如何通过他们的论点?

Is it OK to pass pandas GroupBy functions as argument in python function? and how should I pass their arguments?

我想要一个将 GroupBy 操作(例如 mean()、max())作为参数的函数。我不确定如何包含这些函数的参数。例如,在分位数的情况下,有告诉分位数的参数,所以在这种情况下我应该能够提供这个额外的参数。

def compute_moment(data, moment = pd.core.groupby.GroupBy.mean):

    # This builds columns that we will use to group.
    group_data = data.rank(pct = True).round(1).add_suffix('_grouper')
    df = data.join(group_data)

    out = []
    for col in data.columns:
        #This is the key step, what if I want moment to be, say quantile(q = .7)?
        x = df.groupby(col+'_grouper').mean()[col] #no problem here
        y = moment(df.groupby(col+'_grouper'))['y']

        out += [pd.concat([x, y], axis=1)]

    return out

>>> out = compute_moment(data, pd.core.groupby.GroupBy.mean)

#output is a list of dataframes like this one:
>>> print out[0]

              rho         y
rho_grouper                    
0.0          0.024998  0.035754
0.1          0.099908  0.036522
0.2          0.199903  0.032319
0.3          0.299908  0.038726
0.4          0.399907  0.034523
0.5          0.499907  0.031123
0.6          0.599909  0.031352
0.7          0.699908  0.030531
0.8          0.799902  0.031277
0.9          0.899904  0.028456
1.0          0.974912  0.029378

我想知道如何正确地做到这一点,或者为什么不,有一个更简单的替代方法来拥有一个应用这些 groupby 操作的函数,并让我在必要时传递参数。

顺便问一下,可以将 pandas.GroupBy 函数作为参数传递吗?

你可以传递任何你想要的东西,只要它有效并且对你有用。 您可以将函数的 agrs 作为附加 dict/tuple 参数传递,或者只使用 *args 和 **kwargs。

仍然不清楚您想在这里实现什么。 首先,看起来您在函数中弄乱了 datadf。 其次,如果我理解正确,pd.core.groupby.GroupBy 是数据对象的 class - 这是您将从 df.groupby 获得的,而不是相反。因此,你不应该在这里使用它。

但是,您可以简单地将字符串或聚合函数作为参数传递,然后在 .agg 方法中应用它们:

def foo(df, agg='mean'):
    momentum = df.groupby('grouper').agg(agg)

通过这种方式,您可以将字符串('mean'、'sum')或数组、字典,甚至函数传递到 agg参数中。此外,在这种情况下,数组将导致将数组中的所有函数应用于所有列,因此您不必加入也不必循环。

要详细了解 groupby 的工作原理,请查看此处,例如: https://chrisalbon.com/python/pandas_apply_operations_to_groups.html