python - 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 个作为参数提供的列进行分组)
任何人都可以帮忙吗?
解决方案
在 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
推荐阅读
- eclipse - Eclipse 初学者问题 - 通过文件资源管理器的 SSH shell 未按预期工作
- amazon-web-services - 如何设计关键模式以使每个应用程序只有一个 DynamoDB 表?
- cordova - 如何使threejs画布不被键盘调整大小
- c# - C# WindowsForms PictureBox:控制坐标和图像中像素位置之间的转换
- c# - 为什么不调用这个 C# 实例构造函数,除非有对非静态成员的引用?
- javascript - 要使用数组值更新的对象值
- angular - Angular 材质每 2 个字符后添加分号
- java - 将 .txt 文件转换为一个 .csv。导出的信息会覆盖第一行。有小费吗?
- r - R data.table 到 xts 与分组
- prestashop - Prestashop 自定义页面与自己的模板