使用 Pandas 绘制日期时间每小时的直方图。

9
假设我有一个 pandas.DataFrame 中的 datetime 时间戳列。以秒为单位,为了举例说明,我想将事件分入 10 分钟 [1] 的 bucket / bin 中。我了解可以将 datetime 表示为整数时间戳,然后使用直方图。是否有更简单的方法?pandas 中是否有内置的方法?
[1] 10 分钟仅为示例。最终,我希望使用不同的分辨率。

1
这个代码可能会接近你想要的效果:df.groupby(pd.TimeGrouper(freq='10Min')).mean().plot(kind="bar") 你可以将"bar"替换为"hist",但我不确定这是否有很多意义。我猜测y轴应该是频率,但x轴应该是什么呢?你有原始数据的示例和图表应该是什么样子的示例吗(即使只是口头描述)? - johnchase
1个回答

21

如果您想使用自定义频率,如“10Min”,则需要使用操作indexTimeGrouper(正如 @johnchase 所建议的)。

# Generating a sample of 10000 timestamps and selecting 500 to randomize them
df = pd.DataFrame(np.random.choice(pd.date_range(start=pd.to_datetime('2015-01-14'),periods = 10000, freq='S'), 500),  columns=['date'])
# Setting the date as the index since the TimeGrouper works on Index, the date column is not dropped to be able to count
df.set_index('date', drop=False, inplace=True)
# Getting the histogram
df.groupby(pd.TimeGrouper(freq='10Min')).count().plot(kind='bar')

使用to_period

还可以使用to_period方法,但据我所知,它不适用于自定义时间段,例如"10Min"。此示例使用附加列模拟项目的类别。

输入图像描述

# The number of sample
nb_sample = 500
# Generating a sample and selecting a subset to randomize them
df = pd.DataFrame({'date': np.random.choice(pd.date_range(start=pd.to_datetime('2015-01-14'),periods = nb_sample*30, freq='S'), nb_sample),
                  'type': np.random.choice(['foo','bar','xxx'],nb_sample)})

# Grouping per hour and type
df = df.groupby([df['date'].dt.to_period('H'), 'type']).count().unstack()
# Droping unnecessary column level
df.columns = df.columns.droplevel()
df.plot(kind='bar')

这里输入图片描述


这让我更接近了。谢谢。我还有两个问题:1)x轴刻度与数据的日期时间属性无关,2)"柱状图的总和"不应该是500吗? - Dror
应该使用.plot(kind='bar')而不是像@johnchase建议的.hist(),对吗? - Dror
抱歉,我的第一个回答有一个大错误(太快了不是解决方案)。我刚刚编辑过它并认为现在解决了你的问题。现在“sum”是500 :-) - Romain
这里有一个带有一些示例的笔记本 http://nbviewer.jupyter.org/gist/drorata/e58b673fd87edfc92960 - Dror
这个答案非常有用。谢谢。 - stackoverflowuser2010
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接