在pandas聚合函数中创建多个列

Dav*_*son 9 python time-series pandas

我想在重新采样pandas DataFrame时创建多个列,就像内置的ohlc方法一样.

def mhl(data):
    return pandas.Series([np.mean(data),np.max(data),np.min(data)],index = ['mean','high','low'])

ts.resample('30Min',how=mhl)
Run Code Online (Sandbox Code Playgroud)

死了

Exception: Must produce aggregated value
Run Code Online (Sandbox Code Playgroud)

有什么建议?谢谢!

Zel*_*ny7 8

您可以将函数字典传递给resample方法:

In [35]: ts
Out[35]:
2013-01-01 00:00:00     0
2013-01-01 00:15:00     1
2013-01-01 00:30:00     2
2013-01-01 00:45:00     3
2013-01-01 01:00:00     4
2013-01-01 01:15:00     5
...
2013-01-01 23:00:00    92
2013-01-01 23:15:00    93
2013-01-01 23:30:00    94
2013-01-01 23:45:00    95
2013-01-02 00:00:00    96
Freq: 15T, Length: 97
Run Code Online (Sandbox Code Playgroud)

创建函数字典:

mhl = {'m':np.mean, 'h':np.max, 'l':np.min}
Run Code Online (Sandbox Code Playgroud)

将字典传递给how参数resample:

In [36]: ts.resample("30Min", how=mhl)
Out[36]:
                      h     m   l
2013-01-01 00:00:00   1   0.5   0
2013-01-01 00:30:00   3   2.5   2
2013-01-01 01:00:00   5   4.5   4
2013-01-01 01:30:00   7   6.5   6
2013-01-01 02:00:00   9   8.5   8
2013-01-01 02:30:00  11  10.5  10
2013-01-01 03:00:00  13  12.5  12
2013-01-01 03:30:00  15  14.5  14
Run Code Online (Sandbox Code Playgroud)

  • 使用"均值"比使用`np.mean`要快10倍.同样适用于''min'和'max'` (2认同)
  • 有没有办法为大多数列指定默认值(例如,`sum`而不是`mean`)然后覆盖单个列的方法? (2认同)