![](/img/trans.png)
[英]unstack date/hour dataframe into single column with datetime index - python, pandas
[英]Pandas (Python) Splitting hour and time interval on Index and Column
我测量了温度,我想从中创建一个热图。 为此,我首先必须创建一个 DataFrame,其中索引和列上有小时和 15 分钟的间隔。
源数据是这样的:
日期 | 温度 |
---|---|
2021-08-14 11:14:00 | 27.8 |
2021-08-14 11:15:00 | 27.9 |
2021-08-14 11:16:00 | 27.9 |
2021-08-14 11:17:00 | 27.9 |
2021-08-14 11:18:00 | 27.9 |
.... | .... |
2021-08-14 11:31:00 | 28.10 |
2021-08-14 11:32:00 | 28.10 |
2021-08-14 11:33:00 | 28.10 |
2021-08-14 11:34:00 | 28.10 |
我想要得到的是:
日期 | 00 | 15 | 30 | 45 |
---|---|---|---|---|
11:00 | 27.8 | 27.9 | 28.1 | 28.3 |
12:00 | .. | .. | .. | .. |
因此,我希望将一小时内的时间间隔拆分为列和包含特定时间(列发生的时间)的索引。
在 Pandas 中有什么方法可以轻松完成此操作?
提前致谢!
让我们首先将小时和分钟分开(四舍五入为 15),将它们放回 dataframe 并使用.pivot_table()
以间隔方式构建您的 dataframe:
>>> h = df['date'].dt.strftime('%H:00').rename('hour')
>>> m = df['date'].dt.floor(freq='15T').dt.minute.rename('minutes')
>>> df.join([h, m]).pivot_table(index='hour', columns='minutes', values='temperature', aggfunc='mean')
minutes 0 15 30 45
hour
2021-08-14 11:00:00 28.709492 28.026066 27.991953 28.096947
2021-08-14 12:00:00 27.877558 28.022282 27.720347 28.201100
2021-08-14 13:00:00 27.739935 NaN NaN NaN
使用resample
和pivot_table
获得预期结果:
out = df.set_index('date').resample('15T').mean()
out = pd.pivot_table(out, index=out.index.strftime('%H:00'),
columns=out.index.strftime('%M'),
values='temperature')
out = out.rename_axis(index=None, columns=None)
>>> out
00 15 30
11:00 27.8 27.9 28.1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.