您可以将可调用对象(在本例中为函数)传递给how,只要它返回一个标量:
In [31]: from scipy.stats.mstats import gmean
In [32]: import pandas.util.testing as tm
In [33]: ts = tm.makeTimeSeries()[:10]
In [34]: ts
Out[34]:
2000-01-03 0.605
2000-01-04 -0.167
2000-01-05 0.365
2000-01-06 -0.206
2000-01-07 -1.156
2000-01-10 -0.219
2000-01-11 1.704
2000-01-12 -0.148
2000-01-13 1.169
2000-01-14 0.823
Freq: B, dtype: float64
In [35]: ts.resample('2D', how=lambda x: gmean(x).item())
Out[35]:
2000-01-03 0.605
2000-01-05 0.365
2000-01-07 0.000
2000-01-09 0.000
2000-01-11 1.704
2000-01-13 0.981
dtype: float64
请注意,您必须在item此处调用该方法才能获得标量结果(因为取决于您可能获得的值 a MaskedConstant)。pandas不认为单个元素Series是标量。
此外,请注意包含nans 或值的计算结果,其中计算几何平均值可能会返回一个复数值(例如,负数的 4 次根;这将nan在 numpy 中返回)。
gmeanitem当您调用该方法时,会将这样的计算变成 0 。
例如,这就是在2000-01-07和处有零的原因2000-01-09。
在2000-01-07pandasnan为第 2 天填写 a (记住我们在2D这里做的)所以几何平均值计算为ma.exp(ma.mean(ma.log([-1.156, nan])))。这两个值不是“有效”输入ma.log(因此它们被屏蔽),因此ma.mean()返回MaskedConstant其_data属性为0,因此其item方法返回 0。