gpt4 book ai didi

python pandas 按一天中的小时求和

转载 作者:太空狗 更新时间:2023-10-29 20:51:07 26 4
gpt4 key购买 nike

我正在使用以下每小时计数 (df) 的数据集:datframe 有 8784 行(2016 年,每小时)。

dataframe (df)

我想看看是否有每日趋势(例如,早上时间是否有所增加。为此,我想创建一个具有一天中的小时(从 0 到 24)的图x 轴和 y 轴上的骑车人数量(类似于下图中来自 http://ofdataandscience.blogspot.co.uk/2013/03/capital-bikeshare-time-series-clustering.html 的图片)。

enter image description here

我尝试了 pivotresampleset_index 的不同方法,并使用 matplotlib 绘制它,但没有成功。换句话说,我找不到一种方法来总结特定时间的每个观察结果,然后为每个工作日绘制这些观察结果

任何想法如何做到这一点?提前致谢!

最佳答案

我想你可以使用 groupby通过 hourweekday 并聚合 sum (或者可能是 mean),最后 reshape unstackDataFrame.plot :

df = df.groupby([df['Date'].dt.hour, 'weekday'])['Cyclists'].sum().unstack().plot()

解决方案 pivot_table :

df1 = df.pivot_table(index=df['Date'].dt.hour, 
columns='weekday',
values='Cyclists',
aggfunc='sum').plot()

示例:

N = 200
np.random.seed(100)
rng = pd.date_range('2016-01-01', periods=N, freq='H')
df = pd.DataFrame({'Date': rng, 'Cyclists': np.random.randint(100, size=N)})
df['weekday'] = df['Date'].dt.weekday_name
print (df.head())
Cyclists Date weekday
0 8 2016-01-01 00:00:00 Friday
1 24 2016-01-01 01:00:00 Friday
2 67 2016-01-01 02:00:00 Friday
3 87 2016-01-01 03:00:00 Friday
4 79 2016-01-01 04:00:00 Friday

print (df.groupby([df['Date'].dt.hour, 'weekday'])['Cyclists'].sum().unstack())
weekday Friday Monday Saturday Sunday Thursday Tuesday Wednesday
Date
0 102 91 120 53 95 86 21
1 102 83 100 27 20 94 25
2 121 53 105 56 10 98 54
3 164 78 54 30 8 42 6
4 163 0 43 48 89 84 37
5 49 13 150 47 72 95 58
6 24 57 32 39 30 76 39
7 127 76 128 38 12 33 94
8 72 3 59 44 18 58 51
9 138 70 67 18 93 42 30
10 77 3 7 64 92 22 66
11 159 84 49 56 44 0 24
12 156 79 47 34 57 55 55
13 42 10 65 53 0 98 17
14 116 87 61 74 73 19 45
15 106 60 14 17 54 53 89
16 22 3 55 72 92 68 45
17 154 48 71 13 66 62 35
18 60 52 80 30 16 50 16
19 79 43 2 17 5 68 12
20 11 36 94 53 51 35 86
21 180 5 19 68 90 23 82
22 103 71 98 50 34 9 67
23 92 38 63 91 67 48 92

df.groupby([df['Date'].dt.hour, 'weekday'])['Cyclists'].sum().unstack().plot()

graph

编辑:

您还可以将 wekkday 转换为 categorical按星期名称正确排序列:

names = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday','Friday', 'Saturday', 'Sunday']
df['weekday'] = df['weekday'].astype('category', categories=names, ordered=True)
df.groupby([df['Date'].dt.hour, 'weekday'])['Cyclists'].sum().unstack().plot()

graph1

关于python pandas 按一天中的小时求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43585988/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com