在过滤掉反向重复之后,我必须计算有多少个实际的重复。这是我的(工作示例)代码,它太慢了,虽然,为90000 +行。使用iterrows:
import pandas as pd
data = {'id_x':[1,2,3,4,5,6],
'ADDICTOID_x':['BFO:0000023', 'MF:0000016', 'BFO:0000023', 'MF:0000016', 'MF:0000016', 'ADDICTO:0000872'],
'PMID':[34116904, 34116904, 34112174, 34112174, 34112174, 22429780],
'LABEL_x':['role', 'human being', 'role', 'human being', 'human being', 'FDA'],
'id_y':[11,12,13,14,15,16],
'ADDICTOID_y':['MF:0000016', 'BFO:0000023', 'MF:0000016', 'BFO:0000023', 'BFO:0000023', 'ADDICTO:0000904'],
'LABEL_y':['human being', 'role', 'human being', 'role', 'role', '']}
dcp = pd.DataFrame(data)
dcp = dcp.drop(dcp[dcp.LABEL_x == dcp.LABEL_y].index)
for index, row in dcp.iterrows(): # THIS IS SLOW
if ((dcp['ADDICTOID_x'] == row['ADDICTOID_y'])
& (dcp['ADDICTOID_y'] == row['ADDICTOID_x'])
& (dcp['PMID'] == row['PMID'])).any(): # Does the inverse of this row exist in the table?
dcp.drop(index, inplace=True)
print("dcp after drop: ")
print(dcp)
我不能只使用dcp.duplicated(subset=['ADDICTOID_x', 'ADDICTOID_y'], keep='first')
,因为它删除了所有的重复项(有很多),我只想一个接一个地做它们,'PMID'也需要匹配。类似地,(dcp.ADDICTOID_x + dcp.ADDICTOID_y).isin(dcp.ADDICTOID_y + dcp.ADDICTOID_x) & (dcp.PMID == dcp.PMID)
查找到处都有重复的行。逐一迭代和测试是我发现的唯一有效的方法,但它太慢了。有人知道解决这个问题的方法吗?
过滤完反向重复项后,我这样计数:data_chord_plot = dcp.groupby(['LABEL_x', 'LABEL_y'], as_index=False)[['PMID']].count() data_chord_plot.columns = ['source','target','value']
编辑:在这个简单的例子中,删除了第1行和第3行,因为它们是第2行和第4行的逆重复。
编辑:我需要删除"镜像"。在两列上具有逆重复的行的映像,但每一行只有一个重复。有些行没有镜像
正确输出(慢)示例:
id_x ADDICTOID_x PMID LABEL_x id_y ADDICTOID_y LABEL_y
1 2 MF:0000016 34116904 human 12 BFO:0000023 role
3 4 MF:0000016 34112174人14 BFO:0000023角色
4 5 MF:0000016 34112174人15 BFO:0000023角色
6 ADDICTO:0000872 22429780 FDA 16 ADDICTO:0000904
创建ADDICTOID_xy
的排序元组,并将drop_duplicates
用于正确的子集:
dcp['ADDICTOID'] = dcp[['ADDICTOID_x', 'ADDICTOID_y']].apply(sorted, axis=1)
.apply(tuple)
out = dcp.drop_duplicates(subset=['ADDICTOID', 'PMID'], keep='first')
>>> out
id_x ADDICTOID_x PMID LABEL_x id_y ADDICTOID_y LABEL_y ADDICTOID
0 1 BFO:0000023 34116904 role 11 MF:0000016 human being (BFO:0000023, MF:0000016)
2 3 BFO:0000023 34112174 role 13 MF:0000016 human being (BFO:0000023, MF:0000016)
5 6 ADDICTO:0000872 22429780 FDA 16 ADDICTO:0000904 (ADDICTO:0000872, ADDICTO:0000904)
也许有更短的方法,但我可以想到将df
与其反向自我合并,然后只留下没有先前匹配的行。所以不用循环输入:
dcp = dcp.merge(dcp[['id_x', 'PMID', 'ADDICTOID_x', 'ADDICTOID_y']].rename({'id_x': 'inv_id', 'ADDICTOID_x': 'inv_y', 'ADDICTOID_y': 'inv_x'}, axis=1), how='left')
dcp['was'] = (dcp['ADDICTOID_x'] == dcp['inv_x']) & (dcp['ADDICTOID_y'] == dcp['inv_y']) & (dcp['id_x'] > dcp['inv_id'])
dcp = dcp.sort_values(['id_x', 'was']).drop_duplicates('id_x', keep='last')
dcp = dcp.loc[~dcp['was'], 'id_x': 'LABEL_y']