【问题标题】:How to pass list of custom functions to pandas.Dataframe.aggregate如何将自定义函数列表传递给 pandas.Dataframe.aggregate
【发布时间】:2018-02-13 12:40:51
【问题描述】:

我正在尝试使用不同的自定义函数聚合 pd.Dataframe,尤其是来自 scipy.stats。我可以让它与单个函数一起工作,在这种情况下trim_mean

import pandas as pd
import numpy as np
from scipy.stats import trim_mean

df = pd.DataFrame(np.random.randn(100, 3), columns=['A', 'B', 'C'], index=pd.date_range('1/1/2000', periods=100))

# this works as expected
df.agg([np.sum, np.mean])

# now with a different function, works also
df.agg(lambda x: trim_mean(x, 0.2))

# apply also works
df.apply(lambda x: trim_mean(x, 0.2))

但是,df.agg([lambda x: trim_mean(x, 0.2)])df.apply([lambda x: trim_mean(x, 0.2)]) 一样会生成 IndexError: tuple index out of range'

我找到了old issue on pandas-dev,但这对我来说没有意义。

帮忙,有人吗?

【问题讨论】:

    标签: python pandas numpy lambda scipy


    【解决方案1】:

    函数列表前需要lambda,返回DataFrame使用Series

    c = ['trim_mean','mean','sum']
    print (df.agg(lambda x: pd.Series([trim_mean(x, 0.2), np.mean(x), np.sum(x)], index=c)))
    

    或者:

    print (df.apply(lambda x: pd.Series([trim_mean(x, 0.2), np.mean(x), np.sum(x)], index=c)))
    

                       A         B         C
    trim_mean  -0.143219 -0.018430 -0.097768
    mean       -0.171887 -0.042308 -0.004843
    sum       -17.188738 -4.230797 -0.484343
    

    验证:

    print (df.agg([np.sum, np.mean]))
                  A         B         C
    sum  -17.188738 -4.230797 -0.484343
    mean  -0.171887 -0.042308 -0.004843
    
    print(df.agg(lambda x: trim_mean(x, 0.2)))
    A   -0.143219
    B   -0.018430
    C   -0.097768
    dtype: float64
    

    【讨论】:

      【解决方案2】:

      您将列表作为参数提供,并且它们都期望某些功能,因此请使用:

      df.agg(*[lambda x: trim_mean(x, 0.2)])
      

      或者:

      df.apply(*[lambda x: trim_mean(x, 0.2)])
      

      从列表中解压缩这些函数作为参数。

      但是,如果您有多个 lambdas,您将遇到您在 Google 上搜索的错误,因为它们具有相同的名称。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多