【发布时间】:2022-10-13 16:21:28
【问题描述】:
我需要分组和聚合数据框。
有些列具有特定的聚合功能,其余的我想使用first。
我只是不想硬编码其余的列名,因为它可能因大小写而异。你有什么优雅的想法如何实现吗?
import pandas as pd
df = pd.DataFrame({"col1": [1,2,3,4,5],
"col2": ["aa","aa","bb","bb","cc"],
"col3": ["b","b","b","b","b"],
"col4": ["c","c","c","c","c"],
"col5": [11,12,13,14,15]}
)
df.groupby(["col2"]).agg({
"col1": "mean",
"col5": "max",
"col3": "first",
"col4": "first"
})
输出:
col1 col5 col3 col4
col2
aa 1.5 12 b c
bb 3.5 14 b c
cc 5.0 15 b c
但我不想明确指定
"col3": "first",
"col4": "first"
简单地说,groupby 和 agg 中未使用的所有列都应使用默认函数进行聚合。
【问题讨论】:
-
有关使用字典设置默认函数的方法,请参见副本。在您的情况下,您可以使用
d = {c: 'first' for c in df.columns} ; d['col1'] = 'mean' ; d['col5'] = 'max' ; df.groupby(["col2"]).agg(d)