python - 计数到第一列并总结到其余列 pandas groupby
问题描述
我有一个df
290 列的 pandas DataFrame。
有没有办法根据.groupby
以下规则进行操作:
- 第二列的求和运算。
- 计数操作到第 3 列。
- 对所有其他列的平均操作
我知道我可以这样使用:
df.groupby("column1") \
.agg({"column2":"sum",
"column3":"count",
"column4":"mean",
...
"column290":"mean"})
但是使用这种方式完全没有效率,因为我必须键入所有其他列。
有没有办法设置这个操作?就像我没有将任何设置为 agg 时设置默认功能一样?
解决方案
让我们使用字典:
import pandas as pd
import numpy as np
df=pd.DataFrame(np.arange(100).reshape(10,-1), columns=[*'ABCDEFGHIJ'])
# Defined the first three columns
aggdict={'A':'sum',
'B':'sum',
'C':'count'}
# Use for loop to added to dictoary the rest of the columns. Creating a
# default aggregation method
for i in df.columns[3:]:
aggdict[i]='mean'
# Use agg with dictionary
df.groupby(df.index%2).agg(aggdict)
推荐阅读
- sql - 如何使用相同的数据集更改 2 列或更多列的名称
- agora.io - Agora.io 是否提供类似 whatsapp 的通话功能?
- electron - 如何将文件保存到电子js中的应用程序文件夹
- angular - 忽略路由中的 Angular 11 + ionic 5 runGuardsAndResolvers 标志
- backbone.js - 使用 StickIt 绑定到 Backbone Marionette 的 UI 哈希
- node.js - 这个 if 语句究竟做了什么?
- shell - sed如何过滤以前的冗余条件
- swift - 有什么办法可以在 Xcode 中 StackView 的间距选择中添加乘数
- angular - 尝试运行 Angular 项目后生成的错误
- c - 如何在 typedef 函数上强制执行 SAL 注释?