You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas统计DataFrame中两个时间戳间的小时出现频次?

统计DataFrame时间区间覆盖的整点小时频次

实现步骤

  1. 转换时间列类型
    先把Start Time和End Time列转为pandas的datetime类型,这是后续时间操作的基础。

  2. 生成每行覆盖的整点小时
    对每行的时间区间,提取所有被覆盖的整点小时(比如00:35到05:29覆盖0、1、2、3、4、5点)。核心逻辑是生成从开始时间所在整点到结束时间所在整点的序列,只要结束时间不在整点上,就包含结束时间所在的小时。

  3. 统计小时频次
    将所有行的覆盖小时展开,统计每个小时的出现次数。


完整代码示例

import pandas as pd
from collections import Counter

# 1. 准备示例数据并转换时间类型
data = {
    'Start Time': ['2022-01-01 00:35:00', '2022-01-01 00:55:00', '2022-01-01 01:35:00', '2022-01-01 02:29:00'],
    'End Time': ['2022-01-01 05:29:47', '2022-01-01 05:00:17', '2022-01-01 06:26:00', '2022-01-01 04:25:17']
}
df = pd.DataFrame(data)
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['End Time'] = pd.to_datetime(df['End Time'])

# 2. 定义函数生成每行覆盖的整点小时
def get_covered_hours(row):
    # 取开始时间的整点
    start_hour = row['Start Time'].floor('H')
    # 取结束时间的整点
    end_hour = row['End Time'].floor('H')
    # 如果结束时间不在整点,说明覆盖了当前整点小时,需将结束区间后移1小时
    if row['End Time'].minute > 0 or row['End Time'].second > 0:
        end_hour += pd.Timedelta(hours=1)
    # 生成所有整点时间并提取小时数
    hours = pd.date_range(start=start_hour, end=end_hour, freq='H')
    return hours.hour.tolist()

df['Covered Hours'] = df.apply(get_covered_hours, axis=1)

# 3. 统计频次(两种方法任选其一)
# 方法一:用Counter统计
all_hours = []
for hours in df['Covered Hours']:
    all_hours.extend(hours)
hour_counts = Counter(all_hours)
result = pd.DataFrame.from_dict(hour_counts, orient='index', columns=['频次']).sort_index()

# 方法二:用pandas explode展开后统计
# exploded_hours = df['Covered Hours'].explode()
# result = exploded_hours.value_counts().sort_index().rename('频次').to_frame()

# 输出结果
print(result)

运行结果

频次
0    2
1    3
2    4
3    4
4    4
5    3
6    1

内容的提问来源于stack exchange,提问作者Jeff Sedlock

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 08:55:37