python - 在 Pandas 中按时间分组的更快方法

标签 python datetime time group-by pandas

我有一个包含几天 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/

相关文章:

python - 如何使用一个 DF 创建多个绘图

python - 使用 pyinstaller 时 .exe 文件过大

java - 使用 JODA 进行日期格式化 - AM 格式错误

c# - 约会时间? AddDays 扩展方法

iphone - 使用 NSDateFormatter 从字符串中获取日期,无论 12 小时到 24 小时设置如何

r - 将时间字符串转换为时间或数字格式

python - 基于时间戳重新处理 mp4 视频 Python

python - Apache Cassandra Python 插入数据

javascript - 在 Django CharFields 交互中应用条件

python - Numpy 在新版本中将日期对象转换为 datetime64[s]