2015-08-21 81 views
6

有一个时间序列通过DatatimeIndex索引(TS),通过进行10分钟如何使用熊猫10分钟时间序列分组?

index x y z 

ts1  .... 
ts2  .... 
... 

希望将它,我知道如何组1分钟

def group_by_minute(timestamp): 
    year = timestamp.year 
    month = timestamp.month 
    day = timestamp.day 
    hour = timestamp.hour 
    minute = timestamp.minute 
    return datetime.datetime(year, month, day, hour, minute) 

然后

ts.groupby(group_by_minute, axis=0) 

我的定制功能(大致)

def my_function(group): 
    first_latitude = group['latitude'].sort_index().head(1).values[0] 
    last_longitude = group['longitude'].sort_index().tail(1).values[0] 
    return first_latitude - last_longitude 

所以TS数据框一定要包含 '纬度' 和 '经度' 列

当使用TimeGrouper

ts.groupby(pd.TimeGrouper(freq='100min')).apply(my_function) 

我得到了以下错误,

TypeError: cannot concatenate a non-NDFrame object 
+0

你试过'resample'?例如。 'df.resample('1min','mean')'你在做什么聚合 – JoeCondron

+0

@JoeCondron我正在使用APPLY函数应用自定义函数。在我看来,重新采样或TimeGrouper会自动填补空白,即使有一年的时间差距。有没有办法防止这种情况发生?非常感谢 –

+0

您可以传递自定义函数,如:'df.resample('10min',how = my_func)'。它不会填补空白,除非你告诉它。也许你应该发布你想传递的功能和期望的输出。或者,您可以将函数的最后一行调整为“分钟= 10 *(分钟/ 10)”。 – JoeCondron

回答

10

有一个pandas.TimeGrouper为这种事情,你所描述的会是这样的:

agg_10m = df.groupby(pd.TimeGrouper(freq='10Min')).aggregate(numpy.sum) #or other function 
+1

thx。看来,pd.TimeGrouper确实存在,但这里没有记录http://pandas.pydata.org/pandas-docs/stable/api.html –

+0

oops,你是对的。永远不要注意它是无证的。 –

+0

通过应用TimeGrouper获取“TypeError:无法连接非NDFrame对象” –

2

我知道这是旧的,但pd.Grouper()也将实现这一点:

agg_10m = df.groupby(pd.Grouper(freq='10Min')).aggregate(numpy.sum)