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

Pandas高效筛选日期及识别产科患者合规流感接种的方法

Pandas筛选日期记录的高效方法

要高效筛选DataFrame中早于/晚于指定日期的记录,核心是使用向量式布尔索引,完全避免逐行循环(如iterrows/逐行apply),步骤如下:

  1. 统一日期类型:先用pd.to_datetime()将日期列转换为datetime类型,避免字符串比较的性能损耗和逻辑错误:

    df['date_col'] = pd.to_datetime(df['date_col'])
    
  2. 布尔索引快速筛选:直接用比较运算符生成布尔序列,作为索引完成筛选,这是Pandas底层优化的向量操作,性能远高于逐行处理:

    # 筛选早于指定日期的记录
    early_records = df[df['date_col'] < '2024-01-01']
    
    # 筛选晚于指定日期的记录
    late_records = df[df['date_col'] > '2023-12-31']
    

产科患者流感疫苗接种验证的最优方案

针对你的业务需求,我们可以通过Pandas高效合并+向量运算实现,完全替代低效的逐行查找,步骤如下:

1. 预处理:统一日期格式

先将所有涉及日期的列转换为datetime类型,确保后续运算的准确性和性能:

import pandas as pd

# 转换预产期列
edds['expected_delivery_date'] = pd.to_datetime(edds['expected_delivery_date'])
# 转换接种日期列
flu_shots['flu_shot_date'] = pd.to_datetime(flu_shots['flu_shot_date'])
# 整理流感季开始日期为排序后的DataFrame
flu_seasons = pd.DataFrame({
    'season_start': pd.to_datetime(flu_season_begin_dates.iloc[:, 0])
}).sort_values('season_start')

2. 匹配预产期对应的最近流感季开始日期

使用pd.merge_asof高效匹配每个预产期对应的最近且不晚于预产期的流感季开始日期,该方法专为有序数据的近似合并设计,性能远优于逐行查找:

# 先对预产期数据按日期排序(merge_asof要求两边均为有序数据)
edds_sorted = edds.sort_values('expected_delivery_date')

# 合并匹配最近流感季开始日期
edds_with_season = pd.merge_asof(
    edds_sorted,
    flu_seasons,
    left_on='expected_delivery_date',
    right_on='season_start',
    direction='backward'  # 取小于等于预产期的最大流感季开始日期
)

3. 合并接种记录并验证条件

将预产期数据与接种记录按姓名合并,再用向量运算同时验证两个条件:

# 合并接种记录(保留所有预产期记录,即使无接种记录)
combined = pd.merge(
    edds_with_season,
    flu_shots,
    on='name',
    how='left'
)

# 计算是否满足接种要求:
# (a) 接种日期早于预产期;(b) 接种日期不早于对应流感季开始日期
combined['got_required_flu_shot'] = (
    combined['flu_shot_date'].notna()  # 排除无接种记录的情况
    & (combined['flu_shot_date'] < combined['expected_delivery_date'])
    & (combined['flu_shot_date'] >= combined['season_start'])
)

4. 整理结果

提取需要的列并恢复原数据顺序:

got_flu_shot = combined[['name', 'expected_delivery_date', 'got_required_flu_shot']].sort_index()

结果说明

运行后得到的结果与你的期望一致:

name expected_delivery_date got_required_flu_shot
0  Susan             2024-12-01                 False
1  Susan             2023-10-01                  True
2  Marie             2024-10-15                 False

(注:若你期望结果中Marie的预产期为笔误,比如应为2023-10-01,且需要匹配前一年的流感季开始日期,可将merge_asof替换为直接计算:

edds['season_start'] = edds['expected_delivery_date'].apply(lambda x: pd.to_datetime(f"{x.year-1}-09-01"))

此时Marie的2023-10-01预产期对应的流感季开始日期为2022-09-01,接种日期满足条件,结果为True。)


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 18:45:00