简体   繁体   English

如何从时间戳创建每小时/天的seaborn热图,每小时有多个数据点

[英]How to create a seaborn heatmap by hour/day from timestamp with multiple data points per hour

I have a data frame with a date column which is a timestamp .我有一个带有date列的数据框,它是一个timestamp There are multiple data points per hour of a day eg 2014-1-1 13:10, 2014-1-1 13:20 etc. I want to group the data points from the same hour of a specific day and then create a heatmap using seaborn and plot a different column.一天的每小时有多个数据点,例如2014-1-1 13:10, 2014-1-1 13:20等。我想将特定日期同一小时的数据点分组,然后创建一个热图使用 seaborn 并绘制不同的列。

I have tried to use groupby but I'm not sure how to specify i want the hour and day我曾尝试使用groupby但我不确定如何指定我想要的hourday

date             data
2014-1-1 13:10  50
2014-1-1 13:20  51
2014-1-1 13:30  51
2014-1-1 13:40  56
2014-1-1 13:50  67
2014-1-1 14:00  43
2014-1-1 14:10  78
2014-1-1 14:20  45
2014-1-1 14:30  58 

I want to combine the data by its mean value我想按平均值组合数据

You can use dt.strftime('%H') to get the hours, and dt.strftime('%Y-%m-%D') or dt.normalize() for the days您可以使用dt.strftime('%H')获取小时数,使用dt.strftime('%Y-%m-%D')dt.normalize()获取天数

sns.heatmap(df.groupby([df.date.dt.normalize(), df.date.dt.strftime('%H:00')])
   ['data'].mean()
   .rename_axis(index=['day','hour'])
   .unstack(level=0)
)

Output:输出:

在此处输入图片说明


Update : for the weeks, we can use a similar approach更新:几周内,我们可以使用类似的方法

s = (df.groupby([df.date.dt.isocalendar().week,
                 df.date.dt.strftime('%Y-%m-%d'), 
                 df.date.dt.strftime('%H:00')])
       ['data'].mean()
       .rename_axis(index=['week','day','hour'])
    )

fig, axes = plt.subplots(2,2, figsize=(10,10))
for w, ax in zip(s.index.unique('week'), axes.ravel()):
    sns.heatmap(s.loc[w].unstack(level='day'), ax=ax)
    ax.set_title(f'Week {w}')

Output:输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM