如何在 Pandas 中分组,在所有组和 return 参数上具有带参数的函数

How to group by in Pandas, have function with argument on all groups and return argument

我正在积累 Pandas 的经验并遇到了这个挑战:我有一个源数据框,比如 df_source,包含 'A'、'B' 列, 'C'。我想按 'A' 和 'B' 分组,并且每个组都有一个基于 'C' 的所有值的计算。结果应该是一个新的附加列 'D'.

def myfunc(df, par):
    {some complex calculation based on all values of df['C']}
    return [dataframe or column]

df_source['D'] = df_source.groupby(['A', 'B']).{call myfunc per group, and pass parameter value}

我的问题:如何从这里移动到创建列 'D'?据我了解,apply 适用于单行而不适用于组。

更新:在单个组中,每一行可能有不同的 D 值,例如字符串 'i-th element/n-elements in group'.

我觉得你需要flexible apply:

def myfunc(x, p):
    #y => return `Series`
    return y

df_source['D'] = df_source.groupby(['A', 'B'])['C'].apply(lambda x: myfunc(x, par))

另一种可能的解决方案是使用 transform:

df_source['D'] = df_source.groupby(['A', 'B'])['C'].transform(lambda x: myfunc(x, par))