我是Pandas的新手,想将以下简单的R代码转换为Pandas,以计算列的平均值和加权平均值(实际上,还有更多列要聚合)。解决方案必须是可链接的,因为在此计算之前和之后都有多个步骤。我已经看过使用apply函数(Calculate weighted average using a pandas/dataframe)的解决方案,但是随后看来,要么要么必须在apply函数内部执行完整的聚合步骤(所有列,可能所有不相关的列),但是我发现这很丑陋,或分别计算平均值和加权平均值,然后再进行表联接。在Pandas,最先进的方法是什么?
df = data.frame(batch=c("A", "A", "B", "B", "C","C"), value=1:6, weight=1:6)
df %>%
group_by(batch) %>%
summarise(avg = mean(value), avg_weighted = sum(value*weight)/sum(weight))
# A tibble: 3 x 3
batch avg avg_weighted
<chr> <dbl> <dbl>
1 A 1.5 1.67
2 B 3.5 3.57
3 C 5.5 5.55
这是我的熊猫尝试:
df2 = pd.DataFrame({'batch': ["A", "A", "B", "B", "C", "C"], 'value':[1,2,3,4,5,6], 'weight':[1,2,3,4,5,6]})
def agg_step(grp):
return pd.DataFrame({'avg':[grp['value'].mean()],
'avg_weighted':np.average(grp['value'], weights=grp['weight'])})
(df2.
groupby('batch')
.apply(agg_step)
.reset_index()
.drop(columns='level_1')
)
Out[93]:
batch avg avg_weighted
0 A 1.5 1.666667
1 B 3.5 3.571429
2 C 5.5 5.545455
答案 0 :(得分:0)
这应该有效:
(df2.groupby("batch")
.agg({
"value": [
"mean",
lambda x: np.average(x, weights=df2.loc[x.index, "weight"])
]
}))