python - 使用 pandas groupby + apply 和 condensing groups 计算平均值的更快方法

标签 python pandas pandas-groupby pandas-apply

我想对两个值进行分组,如果该组包含多个元素,则仅返回该组的第一行,并将该值替换为该组的平均值。如果只有一个元素,我想直接返回。我的代码如下所示:

final = df.groupby(["a", "b"]).apply(condense).drop(['a', 'b'], axis=1).reset_index()

def condense(df):
    if df.shape[0] > 1:
        mean = df["c"].mean()
        record = df.iloc[[0]]
        record["c"] = mean
        return(record)
    else:
        return(df)

df 看起来像这样:

a      b     c   d
"f"   "e"    2   True
"f"   "e"    3   False
"c"   "a"    1   True

由于数据框相当大,我有73800个组,整个groupby + apply的计算大约需要一分钟。这太长了。有没有办法让它运行得更快?

最佳答案

我认为一个值的平均值与多个值的平均值相同,因此您可以通过 GroupBy.agg 来简化解决方案列 cmean 和所有其他值按 first 聚合:

d = dict.fromkeys(df.columns.difference(['a','b']), 'first')
d['c'] = 'mean'
print (d)
{'c': 'mean', 'd': 'first'}

df = df.groupby(["a", "b"], as_index=False).agg(d)
print (df)
   a  b    c     d
0  c  a  1.0  True
1  f  e  2.5  True

关于python - 使用 pandas groupby + apply 和 condensing groups 计算平均值的更快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64427301/

相关文章:

python - Pandas:按日期将大文件拆分为单独的文件,保留原始顺序。

python - Django Nonrel - 无法登录开发服务器上的管理面板

python - Tensorflow 多 GPU 重用与复制?

python - 两个子图的单个颜色条更改其中一个子图的大小

python - 如何按 pandas 数据框中每一天的时间戳进行分组并将其写入 csv?

python - 根据变量字段进行分组,然后重置python中的计数器(cumcount)

python - 我在 python 的 Flask 教程的开头,我不明白这一段

python - Pandas 忽略缺失的日期来查找百分位数

python - Python中基于中值的线性回归

python - groupby 并选择每个组的第一个、第二个和第四个成员?