1 python group-by time-series pandas
我有以下数据:
timestamp, country_code, request_type, latency
2013-10-10-13:40:01, 1, get_account, 134
2013-10-10-13:40:63, 34, get_account, 256
2013-10-10-13:41:09, 230, modify_account, 589
2013-10-10-13:41:12, 230, get_account, 43
2013-10-10-13:53:12, 1, modify_account, 1003
Run Code Online (Sandbox Code Playgroud)
时间戳是第二个分辨率而不是常规的.
如何在pandas查询中表达如下:
然后在同一图表上绘制所有组的图表,每个组都随着时间的推移而成为自己的行.
更新:
基于1的建议我有:
bycc = df.groupby('country_code').reason.resample('10T', how='count')
bycc.plot() # BAD: uses (country_code, timestamp) on the x axis
bycc[1].plot() # properly graphs the time-series for country_code=1
Run Code Online (Sandbox Code Playgroud)
但似乎找不到简单的方法将每个country_code绘制为一个单独的行,x轴上的时间戳和y上的值.我认为有两个问题(1)每个country_code的时间戳不一样,它们需要在同一个开始/结束时对齐,(2)需要从多索引TimeSeries对象中找到正确的API /方法对于多指数的每个第一个值,单行绘制1行.按我的方式工作......
更新2
以下似乎是这样做的:
i = 0
max = 3
pylab.rcParams['figure.figsize'] = (20.0, 10.0) # get bigger graph
for cc in bycc.index.levels[0]:
i = i + 1
if (i <= max):
cclabel = "cc=%d" % (cc)
bycc[cc].plot(legend=True, label=cclabel)
Run Code Online (Sandbox Code Playgroud)
仅打印最大值,因为它会变得嘈杂.现在要弄清楚如何更好地显示具有大量时间序列的情节.
注意:pandas无法解析日期时间字符串"2013-10-10-13:40:63",因为分钟上额外的4秒(dateutil无法解析; pandas使用dateutil来解析日期).为了便于说明,我把它改为"2013-10-10-13:40:59".
country_code分钟10分钟的请求数量:In [83]: df
Out[83]:
country_code request_type latency
timestamp
2013-10-10 13:40:01 1 get_account 134
2013-10-10 13:40:59 34 get_account 256
2013-10-10 13:41:09 230 modify_account 589
2013-10-10 13:41:12 230 get_account 43
2013-10-10 13:53:12 1 modify_account 1003
In [100]: df.groupby('country_code').request_type.resample('10T', how='count')
Out[100]:
country_code timestamp
1 2013-10-10 13:40:00 1
2013-10-10 13:50:00 1
34 2013-10-10 13:40:00 1
230 2013-10-10 13:40:00 2
dtype: int64
Run Code Online (Sandbox Code Playgroud)
latency由request_type在1分钟分辨率这里也可以采用一种非常类似的方法:
In [107]: df.groupby('request_type').latency.resample('T', how=lambda x: x.quantile(0.99))
Out[107]:
request_type timestamp
get_account 2013-10-10 13:40:00 254.78
2013-10-10 13:41:00 43.00
modify_account 2013-10-10 13:41:00 589.00
2013-10-10 13:42:00 NaN
2013-10-10 13:43:00 NaN
2013-10-10 13:44:00 NaN
2013-10-10 13:45:00 NaN
2013-10-10 13:46:00 NaN
2013-10-10 13:47:00 NaN
2013-10-10 13:48:00 NaN
2013-10-10 13:49:00 NaN
2013-10-10 13:50:00 NaN
2013-10-10 13:51:00 NaN
2013-10-10 13:52:00 NaN
2013-10-10 13:53:00 1003.00
dtype: float64
Run Code Online (Sandbox Code Playgroud)
country_code和request_type10分钟分辨率的请求数这基本上与#1相同,除非您在调用时添加了一个额外的组DataFrame.groupby:
In [108]: df.groupby(['country_code', 'request_type']).request_type.resample('10T', how='count')
Out[108]:
country_code request_type timestamp
1 get_account 2013-10-10 13:40:00 1
modify_account 2013-10-10 13:50:00 1
34 get_account 2013-10-10 13:40:00 1
230 get_account 2013-10-10 13:40:00 1
modify_account 2013-10-10 13:40:00 1
dtype: int64
Run Code Online (Sandbox Code Playgroud)
目前尚不清楚你在绘图方面的要求,请详细说明.