【发布时间】:2019-02-26 17:04:12
【问题描述】:
如何指定自定义聚合函数,以便它们在pandas.DataFrame.aggregate 的列表参数中使用时表现正确?
给定 pandas 中的两列数据框 ...
import pandas as pd
import numpy as np
df = pd.DataFrame(index=range(10))
df['a'] = [ 3 * x for x in range(10) ]
df['b'] = [ 1 -2 * x for x in range(10) ]
...在聚合函数规范列表上进行聚合不是问题:
def ok_mean(x):
return x.mean()
df.aggregate(['mean', np.max, ok_mean])
a b
mean 13.5 -8.0
amax 27.0 1.0
ok_mean 13.5 -8.0
但是当聚合被指定为(lambda 或命名的)函数时,聚合失败:
def nok_mean(x):
return np.mean(x)
df.aggregate([lambda x: np.mean(x), nok_mean])
a b
<lambda> nok_mean <lambda> nok_mean
0 0.0 0.0 1.0 1.0
1 3.0 3.0 -1.0 -1.0
2 6.0 6.0 -3.0 -3.0
3 9.0 9.0 -5.0 -5.0
4 12.0 12.0 -7.0 -7.0
...
混合聚合和非聚合规范会导致错误:
df.aggregate(['mean', nok_mean])
~/anaconda3/envs/tsa37_jup/lib/python3.7/site-packages/pandas/core/base.py in _aggregate_multiple_funcs(self, arg, _level, _axis)
607 # if we are empty
608 if not len(results):
--> 609 raise ValueError("no results")
610
直接使用聚合函数(不在列表中)给出预期结果:
df.aggregate(nok_mean)
a 13.5
b -8.0
dtype: float64
这是一个错误还是我在定义聚合函数的方式上遗漏了什么?在我的真实项目中,我使用了更复杂的聚合函数(例如this percentile one)。所以我的问题是:
如何指定自定义聚合函数以解决此错误?
请注意,在滚动、扩展或分组窗口上使用自定义聚合函数会产生预期的结果:
df.expanding().aggregate(['mean', nok_mean])
## returns cumulative aggregation results as expected
熊猫版本:0.23.4
【问题讨论】: