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

如何在Pandas中匹配交易时间与员工排班时段计算员工小费

员工小费分配实现方案

实现步骤

  • 第一步:统一处理时间字段,转换为可比较的datetime格式
import pandas as pd

# 交易表处理:合并日期+时间为完整交易时间戳
ts_df['transaction_time'] = pd.to_datetime(ts_df['Date'] + ' ' + ts_df['Time'])

# 排班表处理:生成上下班完整时间戳
shift_df['shift_start'] = pd.to_datetime(shift_df['Date'] + ' ' + shift_df['Clock_start'])
shift_df['shift_end'] = pd.to_datetime(shift_df['Date'] + ' ' + shift_df['Clock_end'])

# 若字段已是date/time类型而非字符串,替换拼接逻辑为 astype(str) 即可:
# ts_df['transaction_time'] = pd.to_datetime(ts_df['Date'].astype(str) + ' ' + ts_df['Time'].astype(str))
  • 第二步:匹配交易时段在岗员工,生成带workers列的交易表
# 先按日期关联两张表,过滤出交易时间落在排班区间内的匹配记录
matched_df = ts_df.merge(shift_df, on='Date', how='left')
matched_df = matched_df[
    (matched_df['transaction_time'] >= matched_df['shift_start']) &
    (matched_df['transaction_time'] <= matched_df['shift_end'])
]

# 按交易聚合得到在岗员工列表,和预期输出格式完全一致
ts_with_workers = matched_df.groupby(
    ['Date', 'Time', 'tip'], as_index=False
)['employee'].agg(list).rename(columns={'employee': 'workers'})
  • 第三步:拆分计算每位员工应得小费并汇总
# 单条交易小费按在岗人数均分
matched_df['tip_per_person'] = matched_df['tip'] / matched_df.groupby(
    ['Date', 'Time']
)['employee'].transform('count')

# 统计所有员工累计小费收入
employee_total_tip = matched_df.groupby(
    'employee', as_index=False
)['tip_per_person'].sum().rename(columns={'tip_per_person': 'total_tip'})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:51:02