python-如何将自定义函数列表传递给pandas.Dataframe.aggregate

我正在尝试使用不同的自定义函数(尤其是来自scipy.stats)聚合pd.Dataframe.我可以将其与单个函数一起使用,在这种情况下为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)])会产生IndexError:元组索引超出范围’,与df.apply([lambda x:trim_mean(x,0.2)])一样.

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

帮忙,有人吗?

解决方法:

您需要在函数列表之前使用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
上一篇:scipy和numpy sobel梯度计算之间的差异


下一篇:python-使用pandas数据框和约束最小化距离(K​​nn)