我有一个包含患者、日期、药物和诊断的数据框。 每个患者都有一个唯一的 ID ('pid'),并且可能会或可能不会接受不同的药物治疗。
选择在某个时候接受过某种药物治疗的所有患者的最佳做法是什么? 由于我的数据集非常庞大,for 循环和 if 语句是最后的手段。
例子:
IN:
pid drug
1 A
1 B
1 C
2 A
2 C
2 E
3 B
3 C
3 D
4 D
4 E
4 F
选择在某个时候接受过药物“B”治疗的所有患者。请注意,必须包括该患者的所有条目,这意味着不仅是药物 B 的治疗,还包括所有治疗:
OUT:
1 A
1 B
1 C
3 B
3 C
3 D
我目前的解决方案:
1) 获取包含药物“B”的行的所有 pid
2) 从步骤 1 中获取所有包含 pid 的行。
这个解决方案的问题是我需要用所有 pid(数百万)做一个 loooong if 语句
请您参考如下方法:
我支持COLDSPEED的答案,但如果你说
My current solution: 1) Get all pid for rows that includes drug 'B' 2) Get all rows that include pid from step 1. Problem with this solution is that I need to make a loooong if-statement with all pid's (millions)
可以比硬编码 if 更简单地解决
patients_B = df.loc[df['drug'] == 'B', 'pid]
或
patients_B = set(df.loc[df['drug'] == 'B', 'pid])
然后
result = df[df['pid'].isin(patients_B)]
