python - pandas groupby 聚合具有多列的自定义函数

标签 python pandas aggregate pandas-groupby

我正在尝试在 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/

相关文章:

列的 Pandas 总和滞后

python - Pandas 重建索引并填充缺失值 : "Index must be monotonic"

R 行表示按组(或唯一 ID)在多列上

python - 通过日志记录更新 QTextEdit 时 PyQt5 程序崩溃

python - BeautifulSoup 4 : How to replace a tag with text and another tag?

python - PyMySQL 连接到远程数据库

Django 聚合或注释

Python找到最接近的匹配句子

python - 如何从 pandas read_html 读取并平坦/规范化一系列表?

grid - Kendo - 网格 - 复杂对象的聚合