【问题标题】:histogram with time bins from datetime vector带有来自日期时间向量的时间箱的直方图
【发布时间】:2013-03-06 20:58:33
【问题描述】:

我在 python 中有一个带有日期(日期时间)的向量。如何从该向量上的出现中绘制具有 15 分钟 bin 的直方图?

这是我所做的:

StartTime = []
for b in myEvents:
    StartTime.append(b['logDate'].time())

如您所见,我将日期转换为时间。 (我从 mongoDB 查询中获取 myEvents)

fig2 = plt.figure()
ax = fig2.add_subplot(111)
ax.grid(True,which='both')
ax.hist(StartTime,100)

我得到的错误是:

TypeError: can't compare datetime.time to float

我理解错误,但我不知道如何解决它。

非常感谢您的帮助

【问题讨论】:

  • 您必须将time 转换为float,因为这是直方图函数唯一可以理解的内容。您可能会发现 this code 很有帮助。
  • @askewchan 我已经阅读了这个问题,但无法使用它
  • @Floris,感谢您的链接...不可能没有更优雅的方式来做到这一点...。使用您的建议,我需要稍后转换轴再次从 ms 回到 HH:MM...

标签: python datetime matplotlib histogram


【解决方案1】:

如果你想按小时、分钟或秒分类,应该很容易:

ts = np.array([ datetime.time(random.randint(24),*random.randint(60,size=2)) for i in range(100) ])
hist([t.hour for t in ts], bins = 24) # to bin by hour

此外,对于 15 分钟的 bin,但这里的问题是现在的单位是十进制小时:

hist([t.hour + t.minute/60. for t in ts], bins = 24*60/15)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-28
    • 2018-11-25
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 2014-05-22
    • 2015-07-31
    相关资源
    最近更新 更多