按小时统计DataFrame中字符串类型time列的条目数量
按小时分组统计字符串格式时间的条目数量
步骤1:将字符串时间转换为datetime类型
首先需要把字符串格式的time列转换成pandas的datetime类型,才能方便提取小时信息:
import pandas as pd # 转换时间列,若你的时间格式有特殊规则,可指定format参数,比如'%Y-%m-%d %H:%M:%S' df['time'] = pd.to_datetime(df['time'])
步骤2:按小时分组统计数量
利用datetime列的dt.hour属性提取小时,再通过groupby+size()统计每个小时的条目数:
# 按小时分组统计 hour_counts = df.groupby(df['time'].dt.hour).size()
这会返回一个Series,索引是存在数据的小时数(0-23范围),值为对应小时的条目数量。
步骤3:补全所有小时的统计结果(可选)
如果需要确保0-23每个小时都有统计结果(即使该小时没有数据也显示0),可以用reindex补全:
# 补全0到23小时,缺失的小时填充0 hour_counts = hour_counts.reindex(range(24), fill_value=0)
示例效果
假设你的df数据如下:
| time |
|---|
| 2023-10-01 00:15:20 |
| 2023-10-01 00:40:05 |
| 2023-10-01 01:02:30 |
| 2023-10-01 03:59:59 |
处理后hour_counts会输出:
0 2 1 1 2 0 3 1 4 0 ... 23 0 dtype: int64
内容的提问来源于stack exchange,提问作者avxeesh
相关产品推荐
相关产品推荐

