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

Python遍历DataFrame按P_ID筛选Sepsis首次为1时对应的ICULOS值

循环实现版本(符合遍历所有患者ID的需求)

# 初始化字典存储每个患者的首次Sepsis=1对应的ICULOS
result = {}

# 遍历所有唯一的患者ID
for patient_id in df["P_ID"].unique():
    # 筛选当前患者的全部记录
    patient_data = df[df["P_ID"] == patient_id]
    # 筛选该患者Sepsis标记为1的所有记录
    sepsis_positive = patient_data[patient_data["Sepsis"] == 1]
    if len(sepsis_positive) > 0:
        # 取第一条记录的ICULOS值
        result[patient_id] = sepsis_positive["ICULOS"].iloc[0]
    else:
        # 若该患者全程无Sepsis=1的记录,可按需赋值为None/NaN或者跳过存储
        result[patient_id] = None

# 批量打印所有结果
for pid, iculos_val in result.items():
    print(f"P_ID={pid} 首次Sepsis=1对应的ICULOS为:{iculos_val}")

更高效的非循环实现(推荐)

你也可以直接用pandas原生的分组聚合逻辑实现,不需要手动写循环,代码更简洁,处理大数据量性能更高:

# 筛选所有Sepsis=1的记录后按患者ID分组,取每组第一条的ICULOS值,结果转为字典
result = df[df["Sepsis"] == 1].groupby("P_ID")["ICULOS"].first().to_dict()

# 如果需要包含无Sepsis=1记录的患者,可补充以下代码补全空缺值
all_pids = df["P_ID"].unique()
result = {pid: result.get(pid, None) for pid in all_pids}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:45:05