首页 > 解决方案 > Python - Group_by 自定义函数不适用于多列

问题描述

def agg_count(df, group_field):
    grouped = df.groupby(group_field, as_index=False).size()
    #grouped.sort(ascending = False)

    grouped = pd.DataFrame(grouped).reset_index()
    grouped.columns = [group_field, 'Count']
    return grouped

上面的函数,如果我用下面的一列调用它,效果很好:

agg_count(app_snap1_extract, 'APP_STATUS_C')

如果我用多列调用函数,它会失败(我想自定义函数,以便我可以按 N 个作为参数提供的列进行分组)

任何人都可以帮忙吗?

标签: pythonpandasgroup-by

解决方案


在 pandas 中传递多列groupby时,您需要将其作为list.

grouped = df.groupby(['a','b'])

因此,请确保group_field是上面的列表。那可行。

只需像这样更改您的功能:

def agg_count(df, group_field):
    grouped = df.groupby(group_field, as_index=False).size()
    #grouped.sort(ascending = False)

    grouped = pd.DataFrame(grouped).reset_index()
    grouped.columns = group_field + ['Count']
    return grouped

推荐阅读