我有一个数据框df
hour calls received appointment
6:48 4 2 2
4:02 21 3 2
12:52 31 7 4
2:14 32 5 2
6:45 13 3 2
hour
列是string
我想以 1-2
,2-3
的格式按小时计算总和和分组。
我的方法是:
df[['hour','calls','received','appointment']].groupby('hour').sum()
此外,我想每小时检查一次,如果任何一个小时都没有数据,则用零填充。
我希望输出为:
hour calls received appointment
0-1 0 0 0
1-2 0 0 0
2-3 32 5 2
3-4 0 0 0
4-5 21 3 2
5-6 0 0 0
6-7 17 5 4
...
最佳答案
您可以使用 pandas.resmaple
以 hour
为基础,然后计算 ['calls','received','appointment']
的总和,最后将 datetime 重命名为所需格式。
df['time'] = pd.to_datetime(df['hour'])
df = df.set_index('time').resample('H')[['calls','received','appointment']].sum().reset_index()
# rename 2022-07-24 02:00:00 -> (2-3)
df['time'] = df['time'].apply(lambda x: f"{x.hour}-{x.hour+1}")
print(df)
time calls received appointment
0 2-3 32 5 2
1 3-4 0 0 0
2 4-5 21 3 2
3 5-6 0 0 0
4 6-7 17 5 4
5 7-8 0 0 0
6 8-9 0 0 0
7 9-10 0 0 0
8 10-11 0 0 0
9 11-12 0 0 0
10 12-13 31 7 4
关于python - 如何在 Pandas 中按小时分组并检查每小时的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73095800/