python - Pandas 中的自定义聚合表达式

标签 python pandas

我正在尝试进行自定义聚合(以及其他几个标准聚合)。

像这样的东西:

df = pd.DataFrame(
    [["red", 1, 10], ["red", 2, 20], ["green", 5, 15]],
    columns=["color", "x", "y"]
) 

df2 = (
    df
    .groupby(["color"])
    .agg(amt1=("x", "sum"),
         amt2=("x", "mean"),      
         amt3=("y", "sum"),
         # this does not work...
         amt4= (0.9 * (x.sum() - y.mean()) / x.max()) + 1
        )
)

df2

谢谢你的帮助。

最佳答案

我认为不能直接在自定义函数中使用两列 agg ,您在这里有两个选择。要么使用 apply对于这个特定的自定义函数和 concatagg其他的,或使用基于索引的选择。

# option 1
gr = df.groupby(["color"])
df2 = pd.concat([gr.agg(amt1=("x", "sum"), amt2=("x", "mean"), amt3=("y", "sum")), 
                 gr.apply(lambda dfg: (0.9 * (dfg.x.sum() - df.y.mean()) 
                                      / dfg.x.max()) + 1)
                   .rename('amt4')],
                axis=1 )

# option 2
df2 = (df.groupby(["color"])
         .aggregate(amt1=("x", "sum"), amt2=("x", "mean"), amt3=("y", "sum"),
                    amt4= ('x', lambda x: (0.9 * (x.sum() - df.loc[x.index, 'y'].mean()) 
                                          / x.max()) + 1))
      )

只要索引在 df 中是唯一的,两者都会给出相同的结果

在新版本中使用选项 2 需要常规功能 bug description
def named_lambda(x):
     return (0.9 * (x.sum() - df.loc[x.index, 'y'].mean()) / x.max()) + 1

df2 = (df.groupby(["color"])
         .aggregate(amt1=("x", "sum"), amt2=("x", "mean"), amt3=("y", "sum"),
                    amt4= ('x', named_lambda))
)

关于python - Pandas 中的自定义聚合表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61821290/

相关文章:

python - Pandas 数据帧错误 "tuple index out of range"

python-2.7 - 根据其他数据帧中的值选择数据帧行

python - 按索引名称过滤数据框行

python - 为什么转置不能让我用 df.loc ["Y"] 行连接数据帧

python - 使用多个并行线程分部分下载大文件

python - 使用字典键访问对象属性

python - Wing101 默认为 python 2.7,即使我在 Mac 上安装了最新版本

python: urllib2 使用不同的网络接口(interface)

python - 任何/所有 python 短路 : Why doesn't the following work?

python - 使用 Pandas 的独特连接数据框