我有一个包含几天 1 分钟数据的时间序列,我想按一天中的时间对所有天的数据进行平均。
这很慢:
from datetime import datetime
from pandas import date_range, Series
time_ind = date_range(datetime(2013, 1, 1), datetime(2013, 1, 10), freq='1min')
all_data = Series(randn(len(time_ind)), time_ind)
time_mean = all_data.groupby(lambda x: x.time()).mean()
运行将近一分钟!
虽然是这样的:
time_mean = all_data.groupby(lambda x: x.minute).mean()
只需要几分之一秒。
有没有更快的方法来按一天中的时间分组?
知道为什么这么慢吗?
最佳答案
version 0.11 中引入的“lambda 版本”和时间属性在版本 0.11.0 中似乎很慢:
In [4]: %timeit all_data.groupby(all_data.index.time).mean()
1 loops, best of 3: 11.8 s per loop
In [5]: %timeit all_data.groupby(lambda x: x.time()).mean()
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.RuntimeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.RuntimeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.RuntimeError'> ignored
1 loops, best of 3: 11.8 s per loop
对于当前的 master,这两种方法都相当快:
In [1]: pd.version.version
Out[1]: '0.11.1.dev-06cd915'
In [5]: %timeit all_data.groupby(lambda x: x.time()).mean()
1 loops, best of 3: 215 ms per loop
In [6]: %timeit all_data.groupby(all_data.index.time).mean()
10 loops, best of 3: 113 ms per loop
'0.11.1.dev-06cd915'
因此您可以更新到 master 或等待本月发布的 0.11.1。
关于python - 在 Pandas 中按时间分组的更快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17288636/