如何实现我自己的describe()函数在resample()中使用

Pab*_*blo 5 python pandas

我正在使用表示向量(大小和方向)的时间序列数据.我想重新采样我的数据并使用该describe函数作为how参数.

但是,该describe方法使用标准平均值,我想使用特殊函数来平均方向.因此,我describe基于以下的实现实现了我自己的方法pandas.Series.describe():

def directionAverage(x):
    result = np.arctan2(np.mean(np.sin(x)), np.mean(np.cos(x)))
    if result < 0:
        result += 2*np.pi
    return result

def directionDescribe(x):
    data = [directionAverage(x), x.std(), x.min(), x.quantile(0.25), x.median(), x.quantile(0.75), x.max()]
    names = ['mean', 'std', 'min', '25%', '50%', '75%', 'max']
    return Series(data, index=names)
Run Code Online (Sandbox Code Playgroud)

问题是当我这样做时:

df['direction'].resample('10Min', how=directionDescribe)
Run Code Online (Sandbox Code Playgroud)

我得到了这个例外(最后几行显示):

  File "C:\Python26\lib\site-packages\pandas\core\generic.py", line 234, in resample
    return sampler.resample(self)
  File "C:\Python26\lib\site-packages\pandas\tseries\resample.py", line 83, in resample
    rs = self._resample_timestamps(obj)
  File "C:\Python26\lib\site-packages\pandas\tseries\resample.py", line 217, in _resample_timestamps
    result = grouped.aggregate(self._agg_method)
  File "C:\Python26\lib\site-packages\pandas\core\groupby.py", line 1626, in aggregate
    result = self._aggregate_generic(arg, *args, **kwargs)
  File "C:\Python26\lib\site-packages\pandas\core\groupby.py", line 1681, in _aggregate_generic
    return self._aggregate_item_by_item(func, *args, **kwargs)
  File "C:\Python26\lib\site-packages\pandas\core\groupby.py", line 1706, in _aggregate_item_by_item
    result[item] = colg.aggregate(func, *args, **kwargs)
  File "C:\Python26\lib\site-packages\pandas\core\groupby.py", line 1357, in aggregate
    result = self._aggregate_named(func_or_funcs, *args, **kwargs)
  File "C:\Python26\lib\site-packages\pandas\core\groupby.py", line 1441, in _aggregate_named
    raise Exception('Must produce aggregated value')
Run Code Online (Sandbox Code Playgroud)

问题是:我如何实现自己的describe功能,以便它可以使用resample

zac*_*ach 3

groupby您可以将组作为时间单位,而不是重新采样。对于该组,您可以应用您选择的函数,例如 DirectionAverage 函数。

请注意,我导入 TimeGrouper 函数以允许按时间间隔进行分组。

import pandas as pd
import numpy as np
from pandas.tseries.resample import TimeGrouper

#group  your data
new_data = df['direction'].groupby(TimeGrouper('10min'))
#apply your function to the grouped data
new_data.apply(directionDescribe)
Run Code Online (Sandbox Code Playgroud)