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

相关文章

转载:一文讲述Pandas库的数据读取、数据获取、数据拼接、数...
Pandas是一个开源的第三方Python库,从Numpy和Matplotlib的基...
整体流程登录天池在线编程环境导入pandas和xrld操作EXCEL文件...
 一、numpy小结             二、pandas2.1为...
1、时间偏移DateOffset对象DateOffset类似于时间差Timedelta...
1、pandas内置样式空值高亮highlight_null最大最小值高亮背景...