【发布时间】:2021-02-02 05:27:23
【问题描述】:
我想对两个值进行分组,如果该组包含多个元素,则仅返回该组的第一行,并将该值替换为该组的平均值。如果只有一个元素,我想直接返回。我的代码如下所示:
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的计算大约需要一分钟。这太长了。有没有办法让它跑得更快?
【问题讨论】:
标签: python pandas pandas-groupby pandas-apply