我正在尝试在 pandas 中使用带有 groupby
的自定义函数。我发现使用 apply
可以让我通过以下方式做到这一点:
(计算两组新平均值的示例)
import pandas as pd
def newAvg(x):
x['cm'] = x['count']*x['mean']
sCount = x['count'].sum()
sMean = x['cm'].sum()
return sMean/sCount
data = [['A', 4, 2.5], ['A', 3, 6], ['B', 4, 9.5], ['B', 3, 13]]
df = pd.DataFrame(data, columns=['pool', 'count', 'mean'])
df_gb = df.groupby(['pool']).apply(newAvg)
是否可以将其集成到 agg
函数中?按照这些思路:
df.groupby(['pool']).agg({'count': sum, ['count', 'mean']: apply(newAvg)})
最佳答案
国际联合会
df.groupby(['pool']).apply(lambda x : pd.Series({'count':sum(x['count']),'newavg':newAvg(x)}))
Out[58]:
count newavg
pool
A 7.0 4.0
B 7.0 11.0
关于python - pandas groupby 聚合具有多列的自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54183523/