我正在使用表示向量(大小和方向)的时间序列数据。我想resample我的数据并使用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)
问题是当我这样做时:
df['direction'].resample('10Min', how=directionDescribe)
我得到了这个例外(显示了最后几行):
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')
问题是:我如何实现自己的describe
功能,以便它与resample
一起使用?
答案 0 :(得分: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)