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

如何按规则将问卷DataFrame空缺随访日期替换为No answer和too early

调研问卷随访日期校验处理方案

需求说明

需处理1000+行的调研问卷日期数据,问卷共设基线(baseline)、30天、60天、90天四个阶段,以基线日期为参照校验30/60/90天的随访日期更新情况:对应列存在日期即为有效,超出对应天数填写也符合要求。空缺的NA值按以下两个规则替换:

  • No answer:基线日期叠加对应天数(30/60/90天)后仍无填写日期,属于超期未填
  • too early:基线日期叠加对应天数尚未到达,暂不满足填报条件

原始数据结构

BaselineDates_30dDates_60dDates_90d
2019-06-012019-07-1NANA
2019-06-032019-07-3NANA
2019-05-20NANANA
2019-07-012019-08-12019-09-12019-10-1
2019-05-012019-06-12019-07-1NA

期望处理结果

BaselineDates_30dDates_60dDates_90d
2019-06-012019-07-1too earlytoo early
2019-06-032019-07-3No answerNo answer
2019-05-20No answerNo answerNo answer
2019-07-012019-08-12019-09-1too early
2019-05-012019-06-12019-07-1No answer

Python pandas实现代码

import pandas as pd
from datetime import timedelta

# 预处理:转换所有日期列为datetime格式
df['Baseline'] = pd.to_datetime(df['Baseline'])
for col in ['Dates_30d', 'Dates_60d', 'Dates_90d']:
    df[col] = pd.to_datetime(df[col], errors='coerce')

# 自定义统计截止日期,可根据实际业务时间调整
current_date = pd.to_datetime('2019-08-10')

# 定义NA值替换逻辑
def fill_na_status(row, days):
    # 已有日期直接返回格式化后的结果
    if pd.notna(row[f'Dates_{days}d']):
        return row[f'Dates_{days}d'].strftime('%Y-%m-%d')
    # 计算对应随访阶段的截止日期
    follow_deadline = row['Baseline'] + timedelta(days=days)
    return 'too early' if current_date < follow_deadline else 'No answer'

# 批量处理三个随访列
df['Dates_30d'] = df.apply(fill_na_status, axis=1, days=30)
df['Dates_60d'] = df.apply(fill_na_status, axis=1, days=60)
df['Dates_90d'] = df.apply(fill_na_status, axis=1, days=90)

上述逻辑处理1000+行数据耗时可忽略,调整current_date参数即可适配不同时间的统计需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:36:06