如何用Pandas高效统计每秒并发通话量及分析峰值时段?
高效统计每秒并发通话数的Pandas实现
问题背景
现有包含dateTimeConnect(接通时间)和dateTimeDisconnect(挂断时间)的通话记录数据集,需要统计数据覆盖时段内每秒的并发通话数,并分析每日峰值。原实现通过循环遍历每秒的方式效率极低,尤其当数据覆盖周期较长(如一周)时性能瓶颈明显。
示例数据集:
import pandas as pd from datetime import timedelta df = pd.DataFrame({ 'dateTimeConnect': pd.to_datetime([ '2020-11-07 08:01:02', '2020-11-07 08:01:19', '2020-11-07 08:01:44', '2020-11-07 08:02:10', '2020-11-07 08:03:01' ]), 'dateTimeDisconnect': pd.to_datetime([ '2020-11-07 08:02:39', '2020-11-07 08:02:08', '2020-11-07 08:02:05', '2020-11-07 08:03:30', '2020-11-07 08:04:15' ]) })
高效实现方案
核心思路是基于事件点的差分累加:将每通电话的接通/挂断视为+1/-1的事件,通过排序事件时间并计算累加和得到并发数,最后补全每秒时间序列,避免逐秒循环。
步骤1:构造事件数据集
将每条通话记录拆分为两个事件:接通(+1)和挂断(-1):
# 构造接通事件 connect_events = df[['dateTimeConnect']].rename(columns={'dateTimeConnect': 'datetime'}) connect_events['delta'] = 1 # 构造挂断事件 disconnect_events = df[['dateTimeDisconnect']].rename(columns={'dateTimeDisconnect': 'datetime'}) disconnect_events['delta'] = -1 # 合并事件并排序 events = pd.concat([connect_events, disconnect_events]).sort_values('datetime')
步骤2:计算并发通话数的累加序列
通过累加事件的delta值,得到每个事件点的并发数:
# 计算累加和,得到事件点的并发数 events['concurrent_calls'] = events['delta'].cumsum()
步骤3:生成完整的每秒时间序列并补全数据
生成从最早接通时间到最晚挂断时间的每秒时间轴,将事件数据合并到时间轴上,填充缺失值并向前填充(因为相邻事件之间的并发数保持不变):
# 生成完整的每秒时间序列 start_time = df['dateTimeConnect'].min() end_time = df['dateTimeDisconnect'].max() time_axis = pd.date_range(start=start_time, end=end_time, freq='S') # 合并事件数据与时间轴,填充缺失值 concurrent_df = pd.DataFrame({'datetime': time_axis}).merge( events[['datetime', 'concurrent_calls']], on='datetime', how='left' ).fillna(method='ffill') # 处理最后一个时间点(挂断后并发数归0) concurrent_df['concurrent_calls'] = concurrent_df['concurrent_calls'].fillna(0).astype(int)
最终结果
生成的concurrent_df即为每秒的并发通话数统计结果,与原循环方法输出一致,但效率提升几个数量级,尤其适用于大跨度数据:
datetime concurrent_calls 0 2020-11-07 08:01:02 1 1 2020-11-07 08:01:03 1 2 2020-11-07 08:01:04 1 ... 192 2020-11-07 08:04:14 1 193 2020-11-07 08:04:15 0
性能优势
原方法的时间复杂度为O(N*T)(N为通话记录数,T为总秒数),而本方案的时间复杂度为O(N log N)(主要来自事件排序),当数据覆盖周期为一周时,总秒数达604800,效率提升极为显著。
内容的提问来源于stack exchange,提问作者Phill Johntony
相关产品推荐
相关产品推荐

