在python中的timeseries数据帧上绘制已排序的工作日/月

2024-06-16 10:17:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我将一年的交通数据存储在一个数据框中

^{tb1}$

我想看看每小时、每天、每周和每月的流量数据模式。我使用以下脚本完成了此操作:

fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(16,10))
plt.axes(ax[0,0])

countData19_gdf.groupby(['hour','address']).mean().groupby(['hour'])['volume'].mean().plot(x='hour',y='volume')
plt.ylabel("Total averge counts of the stations")

plt.axes(ax[0,1])
countData19_gdf.groupby(['day','address']).mean().groupby(['day'])['volume'].mean().plot(x='day',y='volume')

plt.axes(ax[1,0])
countData19_gdf.groupby(['week_of_year','address']).mean().groupby(['week_of_year'])['volume'].mean().plot(x='week_of_year',y='volume', rot=90)
plt.ylabel("Total averge counts of the stations")

plt.axes(ax[1,1])
countData19_gdf.groupby(['month','address']).mean().groupby(['month'])['volume'].mean().plot(x='month',y='volume', rot=90)
plt.ylabel("Total averge counts of the stations")

ax[0,0].title.set_text('Hourly')
ax[0,1].title.set_text('Daily')
ax[1,0].title.set_text('Weekly')
ax[1,1].title.set_text('Monthly')

plt.savefig('temporal_global.png')

结果是这样的,工作日是,月份不是

enter image description here

你能帮我分类吗?我尝试将天作为整数排序,但它不起作用


Tags: of数据textplottitleaddresspltax
1条回答
网友
1楼 · 发布于 2024-06-16 10:17:27

groupby方法将自动对索引进行排序,但是对于字符串值,这意味着按字母顺序排序(而不是按工作日的顺序)

您可以使用reindex方法以您希望的方式对索引进行排序。例如:

countData19_gdf.groupby(['day','address']).mean().groupby(['day'])['volume'].mean().reindex(['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']).plot(x='day',y='volume')

注意:

如果索引中的值不在reindex方法中指定的值列表中,则该行将不包括在内。同样,如果该列表中有一个新值,而该值在索引中不存在,那么它将导致为该新索引分配一个NaN值。因此,如果您的countData19_gdf没有day例如Monday,它将出现在重新索引的df中,但该值将设置为NaN

编辑:

由于您已经有了工作日的数值(您可能希望在几个月内得到相同的数值),为了避免手动指定新索引,您可以通过以下方式获得排序字符串值:

countData19_gdf.sort_values(by = 'weekday')['day'].unique()

快速示例(我更改了给定数据中的一些“日”值以显示问题):

df.groupby(['day','address']).mean().groupby(['day'])['volume'].mean().plot(x='day',y='volume')

产出:

enter image description here

df.groupby(['day','address']).mean().groupby(['day'])['volume'].mean().reindex(['Tuesday','Wednesday','Friday']).plot(x='day',y='volume')

产出:

enter image description here

相关问题 更多 >