2013-02-01 78 views
9

我有多天的日内回报系列,我希望将其缩减为每日ohlc。我可以做类似熊猫 - 按日期分组日内时间序列

hi = series.resample('B', how=lambda x: np.max(np.cumsum())) 
low = series.resample('B', how=lambda x: np.min(np.cumsum())) 

但是,在每次调用时计算cumsum似乎效率低下。有没有办法先计算cumsums,然后对数据应用'ohcl'?

1999-08-09 12:30:00-04:00 -0.000486 
1999-08-09 12:31:00-04:00 -0.000606 
1999-08-09 12:32:00-04:00 -0.000120 
1999-08-09 12:33:00-04:00 -0.000037 
1999-08-09 12:34:00-04:00 -0.000337 
1999-08-09 12:35:00-04:00 0.000100 
1999-08-09 12:36:00-04:00 0.000219 
1999-08-09 12:37:00-04:00 0.000285 
1999-08-09 12:38:00-04:00 -0.000981 
1999-08-09 12:39:00-04:00 -0.000487 
1999-08-09 12:40:00-04:00 0.000476 
1999-08-09 12:41:00-04:00 0.000362 
1999-08-09 12:42:00-04:00 -0.000038 
1999-08-09 12:43:00-04:00 -0.000310 
1999-08-09 12:44:00-04:00 -0.000337 
... 
1999-09-28 06:45:00-04:00 0.000000 
1999-09-28 06:46:00-04:00 0.000000 
1999-09-28 06:47:00-04:00 0.000000 
1999-09-28 06:48:00-04:00 0.000102 
1999-09-28 06:49:00-04:00 -0.000068 
1999-09-28 06:50:00-04:00 0.000136 
1999-09-28 06:51:00-04:00 0.000566 
1999-09-28 06:52:00-04:00 0.000469 
1999-09-28 06:53:00-04:00 0.000000 
1999-09-28 06:54:00-04:00 0.000000 
1999-09-28 06:55:00-04:00 0.000000 
1999-09-28 06:56:00-04:00 0.000000 
1999-09-28 06:57:00-04:00 0.000000 
1999-09-28 06:58:00-04:00 0.000000 
1999-09-28 06:59:00-04:00 0.000000 

回答

15
df.groupby([df.index.year, df.index.month, df.index.day]).transform(np.cumsum).resample('B', how='ohlc') 

我想这可能是我想要的,但我一定要考。

编辑: zelazny7的repsonse后:

df.groupby(pd.TimeGrouper('D')).transform(np.cumsum).resample('D', how='ohlc') 

作品,也是比我以前的解决方案更有效。

+0

似乎工作正常(使用0.9.1)。现在使用来自@ Zelazny7的'TimeGrouper'技巧而不是'[df.index.year ...]',并且你有一个很好的解决方案。 – cronos

+0

在版本0.10.1中,当使用'DataFrameGroupBy'类的'ohlc'方法时,我得到'NotImplementedError' – Zelazny7

+0

似乎也在0.9.2.dev-61766ec中工作。 – signalseeker

4

我无法得到您的resample建议工作。你有没有运气?这里是聚集在工作日水平的数据,并在一次通过计算OHLC统计方式:

from io import BytesIO 
from pandas import * 

text = """1999-08-09 12:30:00-04:00 -0.000486 
1999-08-09 12:31:00-04:00 -0.000606 
1999-08-09 12:32:00-04:00 -0.000120 
1999-08-09 12:33:00-04:00 -0.000037 
1999-08-09 12:34:00-04:00 -0.000337 
1999-08-09 12:35:00-04:00 0.000100 
1999-08-09 12:36:00-04:00 0.000219 
1999-08-09 12:37:00-04:00 0.000285 
1999-08-09 12:38:00-04:00 -0.000981 
1999-08-09 12:39:00-04:00 -0.000487 
1999-08-09 12:40:00-04:00 0.000476 
1999-08-09 12:41:00-04:00 0.000362 
1999-08-09 12:42:00-04:00 -0.000038 
1999-08-09 12:43:00-04:00 -0.000310 
1999-08-09 12:44:00-04:00 -0.000337""" 

df = read_csv(BytesIO(text), sep='\s+', parse_dates=[[0,1]], index_col=[0], header=None) 

在这里,我创建词典的词典。外键引用要应用函数的列。内键包含您的聚合函数的名称,内部值是您想要应用的函数:

f = {2: {'O':'first', 
     'H':'max', 
     'L':'min', 
     'C':'last'}} 

df.groupby(TimeGrouper(freq='B')).agg(f) 

Out: 
        2 
        H   C   L   O 
1999-08-09 0.000476 -0.000337 -0.000981 -0.000486