大熊猫密谋持续时间不同

时间:2014-12-28 22:59:55

标签: python matplotlib pandas

我有一些像这样的数据

    level   ts
0   1.0 2014-11-27 16:00:28.211950-08:00
1   1.5 2014-12-04 17:54:56.185200-08:00
2   2.1 2014-12-04 17:59:54.303900-08:00
3   2.6 2014-12-04 18:04:54.307770-08:00
4   1.8 2014-12-04 18:09:55.917890-08:00
5   1.1 2014-12-04 18:14:54.977890-08:00
6   1.0 2014-12-04 18:19:56.729060-08:00

我想生成一个图,其中Y轴是水平,X轴是一周内的时间(假设x轴的整个范围是一周,并将时间戳投影到特定位置) 。我想绘制线条(或方框),例如,有2014-12-04 17:54:56.185200-08:002014-12-04 17:59:54.303900-08:00的水平线,其级别为1.5,另一条水平线来自2014-12-04 17:59:54.303900-08:002014-12-04 18:04:54.307770-08:00等级2.1等等。当然,这里的时间戳需要转换为一周内的值。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

我仍然不确定你想要达到的目标,我会猜测你想用工作日+小时+标记 x轴分钟,这可以通过添加新列和设置多个索引来实现,如下所示:

import pandas as pd

df
   level                         ts
0    1.0 2014-11-28 00:00:28.211950
1    1.5 2014-12-05 01:54:56.185200
2    2.1 2014-12-05 01:59:54.303900
3    2.6 2014-12-05 02:04:54.307770
4    1.8 2014-12-05 02:09:55.917890
5    1.1 2014-12-05 02:14:54.977890
6    1.0 2014-12-05 02:19:56.729060

df['weekday'] = pd.DatetimeIndex(df['ts']).weekday
# you may use time if you just need timestamp
# df['time'] = pd.DatetimeIndex(df['ts']).time
df['hour'] = pd.DatetimeIndex(df['ts']).hour
df['minute'] = pd.DatetimeIndex(df['ts']).minute
# after that you construct a new dataframe with desired columns
df1 = df[['level', 'weekday', 'hour', 'minute']]
# then plot it by setting index to weekday and time (hour + minute)
df1.set_index(['weekday', 'hour', 'minute']).plot(kind='bar')

enter image description here

希望这有帮助。