我有一个治疗数据框,我想将它们与合适的对照配对。每个对照只能分配给一种治疗。
如果组相同且对照评分在治疗评分的 +/- 10% 范围内,则治疗与对照相匹配。
我需要进行这种配对,以便尽可能多的治疗获得分配合适的对照。
本质上我想要做一个“无需更换的配对”。
df_treatment = pd.DataFrame({
'id': ['a-1', 'a-2', 'a-3', 'b-1', 'b-2'],
'group': ['A', 'A', 'C', 'C', 'A'],
'score': [200, 230, 210, 390, 202]})
id | 组 | 分数 | |
---|---|---|---|
0 | a-1 | A | 200 |
1 | a-2 | A | 230 |
2 | a-3 | C | 210 |
3 | b-1 | C | 390 |
4 | b-2 | A | 202 |
df_control = pd.DataFrame({
'id': ['x-1', 'y-9', 'y-8', 'y-1', 'x-2', 'x-3'],
'group': ['A', 'A', 'A', 'C', 'C', 'C'],
'score': [180, 218, 210, 200, 400, 380]})
id | 组 | 分数 | |
---|---|---|---|
0 | x-1 | A | 180 |
1 | y-9 | A | 218 |
2 | y-8 | A | 210 |
4 | y-1 | C | 200 |
5 | x-2 | C | 400 |
6 | x-3 | C | 380 |
合并以创建在组中匹配的每一对
df_merged = pd.merge(df_treatment, df_control, on='group',
suffixes=('_treated', '_control'), how='left')
筛选符合分数标准的位置
df_matched = df_merged[
(df_merged['score_control'] >= (df_merged['score_treated'] * 0.9))
& (df_merged['score_control'] <= (df_merged['score_treated'] * 1.1))
][['id_treated', 'group', 'id_control']]
df_matched
id_治疗 | 组 | id_control | |
---|---|---|---|
0 | a-1 | A | x-1 |
1 | a-1 | A | y-9 |
2 | a-1 | A | y-8 |
3 | a-2 | A | y-9 |
4 | a-3 | C | y-1 |
5 | b-1 | C | x-2 |
6 | b-1 | C | x-3 |
7 | b-2 | A | y-9 |
8 | b-2 | A | y-8 |
从这里我想获得一个数据框,其中
id_control
不重复,但保留尽可能多的 id_treated
唯一值。
所以在上面的例子中我们会产生
id_治疗 | 组 | id_control | |
---|---|---|---|
0 | a-1 | A | x-1 |
3 | a-2 | A | y-9 |
4 | a-3 | C | y-1 |
5 | b-1 | C | x-2 |
6 | b-1 | C | x-3 |
8 | b-2 | A | y-8 |
我尝试过使用
df_matched.drop_duplicates(subset='id_control', keep='first')
但这将保留所有 a-1 的配对并删除 a-2 和 b-2 配对,留下更少的处理进行比较:
id_治疗 | 组 | id_control | |
---|---|---|---|
0 | a-1 | A | x-1 |
1 | a-1 | A | y-9 |
2 | a-1 | A | y-8 |
4 | a-3 | C | y-1 |
5 | b-1 | C | x-2 |
6 | b-1 | C | x-3 |
据我了解,您有 treat_id 列,并且您希望保留尽可能多的 treat_id ,每个都有唯一的 control_id 值并删除重复项。
要实现这一点,请使用 pandas
groupby()
函数
df.groupby(["threated_id", "control_id"]).first().reset_index()
groupby()
获取指定的列并根据这两列的唯一组合对 DataFrame 进行分组。
reset_index()
方法用于将分组数据转换回常规DataFrame并重置索引。