熊猫中的自定义聚合表达

时间:2020-05-15 14:10:30

标签: 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

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

我认为无法在agg的自定义函数中直接使用两列,这里有两种选择。对此特定的自定义功能使用apply,将concat与其他agg一起使用,或使用基于索引的选择。

# 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))
)