我有一个关于合并 pandas 数据框的问题。我有两个数据框,如下所示:
df1:
chain cdr3 raw_clonotype_id
TRB CASSARGASGERTDTQYF clonotype1
TRA CAVSVVRNNNARLMF clonotype1
TRA CAVRGNARLMF clonotype4
TRB CASSLYGTGGSGANVLTF clonotype4
df2:
cdr3 chain
CAVSVVRNNNARLMF TRA
CAVRGNARLMF TRA
CASSLYGTGGSGANVLTF TRB
我想将它们合并到 cdr3 上,但只保留两条链(TRB 和 TRA)的克隆型 ID 匹配的行。
要得到这样的结果:
chain cdr3 raw_clonotype_id
TRA CAVRGNARLMF clonotype4
TRB CASSLYGTGGSGANVLTF clonotype4
我尝试过这个:
df3 = df.merge(df2.groupby('cdr3',as_index=False)[['cdr3']].agg(','.join),how='left')
但是输出是:
cdr3 chain
CAVSVVRNNNARLMF TRA
CAVRGNARLMF TRA
CASSLYGTGGSGANVLTF TRB
我想我只需要在上面的行中添加一些内容,但我不知道是什么。
最佳答案
IIUC,可以先合并,再过滤,这里使用GroupBy.transform('nunique')
确保每个克隆型有 2 个唯一值(2 个受体):
df3 = df1.merge(df2, on=['cdr3', 'chain'])
df3 = df3[df3.groupby('raw_clonotype_id')['chain'].transform('nunique').eq(2)]
输出:
chain cdr3 raw_clonotype_id
1 TRA CAVRGNARLMF clonotype4
2 TRB CASSLYGTGGSGANVLTF clonotype4
关于python - 仅当两个值匹配且属于同一 ID 时才合并两个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72290217/