python - 如何在 Pandas 中按小时分组并检查每小时的数据?

标签 python pandas dataframe numpy date

我有一个数据框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.resmaplehour 为基础,然后计算 ['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/

相关文章:

python - 带有索引的 Scikit-learn train_test_split

python - 从 pandas 数据框中删除不完整的年份

python - 将具有重复键的 Pandas DataFrame 转换为字典

python - 如何删除 pandas Dataframe 中的 "mirror copy"行?

python-3.x - 如何在标志从 0 变为 1 之前和之后提取行

python - 在 Bokeh 服务器应用程序中动态添加对象

python - 我不能在python中启动两个并行线程吗,每个线程都有一个forerver循环

python - pandas 从日期范围列中提取开始和结束日期

python - 将包含字典列表的列更改为 DataFrame 中的列

python - 提取 pandas 中特定列名的值