【发布时间】:2021-09-04 10:54:29
【问题描述】:
此循环旨在以 1:4 的比例将 df2 中的主题与 df1 中的主题进行匹配。这里的关键是随机选择主题,同时避免冗余。任何主题都不应匹配两次。 df1 有几千个主题,而 df2 有超过一百万。 df1 中的每个主题都将匹配 df2 中的四个主题,不匹配的将被排除在外。有没有人有提高效率的想法?一种同时节省 RAM 的方法将是理想的。谢谢。
for x in range(4): # 1:4 matching
for index, row in df1.iterrows():
temp = df2.loc[(df2['matched'] != 1) & (df2['race_ethnicity'] == row['race_ethnicity']) & (df2['age'] == row['age']) & ((df2['date1'] > row['date2']) | (df2['date1'].isna()))]
a = temp.sample()
a['matched_subject'] = row['subject_id']
a['matched'] = '1'
a['possible_matches'] = len(temp)
可以简化为这个,但我更愿意继续使用“possible_matches”行进行诊断。
for x in range(4): # 4 because 1:4 matching
for index, row in df1.iterrows():
a = df2.loc[(df2['matched_subject']=='') & (df2['race_ethnicity'] == row['race_ethnicity']) & (df2['age'] == row['age']) & ((df2['date1'] > row['date2']) | (df2['date1'] == 0))].sample()
a['matched_subject'] = row['pid']
澄清:所有行在两个 DataFrame 中都是唯一的,表示将在生存分析中进行比较的受试者列表。 Date1 是结果变量事件的日期时间,存在于两个 DataFrame 中的一小部分主题。日期 2 是自变量事件的日期时间,存在于所有 df1 科目,没有 df2 科目。示例输入包括:
- subject_id(数字)
- race_ethnicity(str,3 个类别)
- 年龄(数字)
- 已匹配(二进制,表示 df2 主题是否与 df1 中的主题匹配)
- Matched_subject(数字,匹配主题的subject_id)
- date1(日期时间。生存模型的结果变量,在两个数据帧中都存在一些而不是其他)
- date2(自变量事件的日期时间。df1 中的每个人都有一个 date2,df2 中没有人有一个 date2。df1 对象的 date2 是他们用于生存分析的索引日期,也可以作为其匹配对象的索引日期没有 date2 变量)
我们希望将 df2 中的四个主题与 df1 中的每个主题进行匹配。 df1 中的 Date2 将是 df2 中匹配主题的索引日期,因此我们有一个条件来确保 df2 中的 date1(结果事件)不会在 df1(索引事件)中的 date2 之前发生
以下是与 df1 匹配的两个 df2 主题的示例。还有一个无与伦比的 df1 和 df2 主题。真正的 df2 足够大,可以匹配所有 df1 的主题。
df1:
| subject_id | race_ethnicity | age | date1 | date2 | matched | matched_subject | possible_matches |
|---|---|---|---|---|---|---|---|
| 3a3r796e | Non-Hispanic white | 55 | (can be present in df1 or df2. if present, must be after date 2 in df1) | 2012-01-01 | 1 | 3a3r796e matching based on df1, therefore these are the same | only important for df2. not important for analysis, just a diagnostic value |
| 1234abcd | Non-Hispanic black | 58 | 2017-01-01 | 2016-01-01 | 0 |
df2:
| subject_id | race_ethnicity | age | date1 | date2 | matched | matched_subject | possible_matches |
|---|---|---|---|---|---|---|---|
| 5c69a756 | Non-Hispanic white | 55 | 2015-01-01 | (cannot be present in df2, by definition) | 1 | 3a3r796e | 571 |
| 7as89f75 | Non-Hispanic white | 55 | 1 | 3a3r796e | 571 | ||
| 6376asef | Hispanic | 42 | 2010-01-01 | 0 |
【问题讨论】:
-
能否请您提供一些示例输入?我可以猜到您的意图,但我宁愿明确定义您的要求。另外:
df1中的行是唯一的吗? -
当然。所有行在两个 DataFrame 中都是唯一的。样本输入包括:subject_id(数字)、race_ethnicity(str,3 个类别)、年龄(数字)、date1(日期时间。生存模型的结果变量,存在于某些而不是其他),date2(事件的日期时间是自变量, df1 中科目的索引日期,df2 中不存在)。我们想为 df1 中的每一个匹配 df2 中的四个主题。 df1 中的 Date2 将是 df2 中匹配主题的索引日期,因此我们有一个条件来确保 df2 中的 date1(结果事件)不会在 df1(索引事件)中的 date2 之前发生
-
当我提到样本输入时,我指的是来自
df1和df2的一小部分数据。您描述了数据,但没有显示它们的实际外观 -
我在原始问题中添加了几个示例。谢谢!