You need to enable JavaScript to run this app. 如何使用pandas查找指定月份所有员工的缺失日期并补全数据
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pandas查找指定月份所有员工的缺失日期并补全数据

实现代码

首先做基础数据预处理,把日期列转为datetime格式,无效值统一转NaN:

import pandas as pd

# 示例数据构造,可替换为自己的数据源读取逻辑
df = pd.DataFrame([
    [11,6,'2021-06-03','-','-','-'],
    [11,7,'2021-06-06',None,None,None],
    [11,8,'2021-06-08',None,None,None],
    [13,5,'2021-06-01',None,None,None],
    [13,7,'2021-06-02',None,None,None],
    [13,7,'2021-06-28',None,None,None]
], columns=['Employee','WH','Date','C3','C4','C5'])

# 预处理:日期转datetime,无效值替换为NaN
df['Date'] = pd.to_datetime(df['Date'])
df = df.replace('-', pd.NA)
# 数值列转为可计算格式
num_cols = ['WH','C3','C4','C5']
df[num_cols] = df[num_cols].apply(pd.to_numeric, errors='coerce')

针对单月工时数据补全缺失行:

# 提取当月完整日期范围
current_month = df['Date'].dt.to_period('M').iloc[0]
all_month_dates = pd.date_range(start=current_month.start_time, end=current_month.end_time, freq='D')

# 生成所有员工+当月所有日期的全量组合索引
all_employees = df['Employee'].unique()
full_idx = pd.MultiIndex.from_product([all_employees, all_month_dates], names=['Employee','Date'])

# 重索引补全缺失行,缺失值统一填0,重置索引得到最终结果
result = df.set_index(['Employee','Date']).reindex(full_idx, fill_value=0).reset_index()

如果数据包含多个月的工时记录,可使用分组处理逻辑:

result_list = []
for month, group in df.groupby(df['Date'].dt.to_period('M')):
    all_dates = pd.date_range(start=month.start_time, end=month.end_time, freq='D')
    emps = group['Employee'].unique()
    idx = pd.MultiIndex.from_product([emps, all_dates], names=['Employee','Date'])
    res_group = group.set_index(['Employee','Date']).reindex(idx, fill_value=0).reset_index()
    result_list.append(res_group)
result = pd.concat(result_list, ignore_index=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 19:18:01