Python 使用pandas groupy+;应用和压缩组

Python 使用pandas groupy+;应用和压缩组,python,pandas,pandas-groupby,pandas-apply,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"

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

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)
a      b     c   d
"f"   "e"    2   True
"f"   "e"    3   False
"c"   "a"    1   True
df看起来像这样:

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)
a      b     c   d
"f"   "e"    2   True
"f"   "e"    3   False
"c"   "a"    1   True

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

我认为一个值的平均值与多个值的平均值相同,因此您可以通过对列
c
使用
mean
简化解决方案,并通过
首先对所有其他值进行聚合:

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

哇,这只花了从58秒到0.1秒的时间,谢谢!