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

如何在Python中基于患者ID条件对DataFrame执行下采样

Pandas 按患者ID下采样实现方案

前置要求

  • 已安装pandas库,代码运行前先导入依赖:
import pandas as pd
  • 原始数据集存储为pandas DataFrame,变量名为df

核心实现逻辑

先提取所有唯一的患者ID,随机抽取指定数量的ID后,再用选中的ID过滤原数据集,保留对应患者的所有行。

完整代码

# 1. 提取所有不重复的患者ID
unique_pids = df['P_ID'].unique()

# 2. 随机抽取2932个患者ID,random_state用于固定抽样结果方便复现,不需要可删除
selected_pids = pd.Series(unique_pids).sample(n=2932, random_state=42).tolist()

# 3. 过滤原数据集得到下采样结果
sampled_df = df[df['P_ID'].isin(selected_pids)].reset_index(drop=True)

结果验证

运行以下代码确认抽样符合要求:

  • 验证选中患者数量:print(sampled_df['P_ID'].nunique()) 输出应为2932
  • 验证字段完整性:print(sampled_df.columns) 输出应包含HR、SBP、DBP、Sepsis、P_ID所有字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:24:04