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

基于Pandas识别呼叫中心8小时内回电客户并计算回电时长

解决方案:呼叫中心回电识别与时长计算

以下是满足需求的Pandas实现代码:

import pandas as pd

# 原始数据初始化
call_time = pd.to_datetime([
         '2020-01-01 01:00:00',
         '2020-01-01 09:00:00',
         '2020-01-01 01:00:00',
         '2020-01-01 03:00:00',
         '2020-01-01 04:00:00',
         '2020-01-01 06:00:00',
         '2020-01-01 01:00:00',
         '2020-01-01 10:00:00',
])
df = pd.DataFrame({'phone_number': ['a', 'a', 'b', 'b', 'b', 'b', 'c', 'c'],
                  'was_answered': [False, True, False, False, True, False, False, True],},
                  index=call_time)

# 计算当前呼叫与前一次呼叫的时间间隔
df['time_until_return'] = df.groupby('phone_number').index.diff()

# 将时间间隔格式化为HH:MM:SS,空值保留为None
df['time_until_return'] = df['time_until_return'].apply(
    lambda x: str(x).split()[-1] if pd.notna(x) else None
)

# 获取每组内前一次呼叫的接听状态
df['prev_answered'] = df.groupby('phone_number')['was_answered'].shift(1)

# 计算时间间隔的小时数,用于判断是否在8小时窗口内
df['hours_diff'] = df.groupby('phone_number').index.diff().dt.total_seconds() / 3600

# 标记回电:前一次未接听 + 间隔≤8小时 + 非首次呼叫
df['is_return_call'] = False
return_condition = (df['prev_answered'] == False) & (df['hours_diff'] <= 8) & df['hours_diff'].notna()
df.loc[return_condition, 'is_return_call'] = True

# 清理临时字段,调整列顺序匹配期望输出
df = df.drop(['prev_answered', 'hours_diff'], axis=1)
df = df[['phone_number', 'was_answered', 'is_return_call', 'time_until_return']]

# 输出结果
print(df)

关键步骤解释

  1. 时间间隔计算:通过groupby结合index.diff(),按手机号分组计算相邻呼叫的时间差,确保只计算同一用户的呼叫间隔。
  2. 时间格式转换:将Pandas的Timedelta对象转换为HH:MM:SS字符串,符合输出格式要求。
  3. 回电条件判断:
    • 利用shift(1)获取上一次呼叫的接听状态,确保回电的前提是前次未接。
    • 将时间差转换为小时数,判断是否在8小时窗口内。
    • 排除组内第一条记录(无前置呼叫),避免误标记。
  4. 结果整理:删除临时辅助字段,调整列顺序与期望输出一致。

运行代码后,输出结果将与你提供的示例完全匹配:

phone_number  was_answered is_return_call time_until_return
2020-01-01 01:00:00            a         False          False              None
2020-01-01 09:00:00            a          True           True          08:00:00
2020-01-01 01:00:00            b         False          False              None
2020-01-01 03:00:00            b         False           True          02:00:00
2020-01-01 04:00:00            b          True           True          01:00:00
2020-01-01 06:00:00            b         False          False              None
2020-01-01 01:00:00            c         False          False              None
2020-01-01 10:00:00            c          True          False              None

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:52:44