我有一个时间戳组织得很好的数据框架,如下所示:
这是一个网站日志,时间戳涵盖了整年。我想将它们按天切分,并显示每小时内的访问量,然后将它们绘制在同一图表中并堆叠在一起。就像下图所示:
我已经成功地将它们按天切分并单独绘制了一天的访问量图表,但我在绘制并将它们堆叠在一起时遇到了麻烦。我主要使用的是Pandas和Matplotlib。
有什么建议和意见吗?非常感谢!
编辑:
我的代码如下:
时间戳是:https://gist.github.com/adamleo/04e4147cc6614820466f7bc05e088ac5
我使用以下代码绘制了整个期间的时间戳密度图:
timestamps_series_all = pd.DatetimeIndex(pd.Series(unique_visitors_df.time_stamp))timestamps_series_all_toBePlotted = pd.Series(1, index=timestamps_series_all)timestamps_series_all_toBePlotted.resample('D').sum().plot()
得到的结果是:
我使用以下代码绘制了一天内的时间戳:
timestamps_series_oneDay = pd.DatetimeIndex(pd.Series(unique_visitors_df.time_stamp.loc[unique_visitors_df["date"] == "2014-08-01"]))timestamps_series_oneDay_toBePlotted = pd.Series(1, index=timestamps_series_oneDay)timestamps_series_oneDay_toBePlotted.resample('H').sum().plot()
现在我卡住了。
非常感谢大家的帮助!
回答:
我想你需要使用pivot
:
#https://gist.github.com/adamleo/04e4147cc6614820466f7bc05e088ac5 to Ldf = pd.DataFrame({'date':L})print (df.head()) date0 2014-08-01 00:05:461 2014-08-01 00:14:472 2014-08-01 00:16:053 2014-08-01 00:20:464 2014-08-01 00:23:22#如果需要的话,将其转换为datetime格式df['date'] = pd.to_datetime(df['date'] )#按小时重采样,获取计数并创建数据框架df = df.resample('H', on='date').size().to_frame('count')#提取日期和小时df['days'] = df.index.datedf['hours'] = df.index.hour#旋转并绘图#可能需要检查来自http://stackoverflow.com/a/33474410/2901002的参数kind='density'#df.pivot(index='days', columns='hours', values='count').plot(rot='90')#编辑:最后一行改为以下内容:df.pivot(index='hours', columns='days', values='count').plot(rot='90')