Skip to main content
 首页 » 编程设计

python之加快 Pandas 数据框中的搜索速度

2025年05月04日17lovecherry

我有一个名为 real_info 的数据框,例如它有 3 列:

  Source   Target Interaction 
0  MAP7D1    APOA1    physical 
1  MAP7D1    RBM48    physical 
2  MAP7D1  GPRASP1    physical 
3  MAP7D1    COPS6    physical 
4   USP20   MAP7D1    physical 

我将这些列像这样索引到一个新的数据框中,认为搜索会很快:

new_df = real_info.set_index(['Source','Target','Interaction']) 

我有 5000 个 name_list 字符串,我在 new_df 中搜索这对字符串。如果有匹配项,那么我将存储在一个文件中,例如:

for names_A in name_list: 
    for names_B in name_list: 
        res = df.query('Source == "{}" & Target == "{}"'.format(names_A,names_B)) 
        if len(res.index.tolist()) > 0: 
            res.to_csv('nets.csv', mode='a', header=False) 

此过程有效,但搜索 5000 X 5000 列表对的速度非常慢。有什么改进的建议吗?

请您参考如下方法:

您实际上已经完成了一半。非常感谢 MaxU,从他的帖子中借用了数据。


第一步
索引是一个不错的选择,但我们只索引前两列:

df = df.set_index(['Source', 'Target']) 
df 
 
              Interaction 
Source Target             
a      z         physical 
b      c         physical 
c      x         physical 
d      y         physical 
e      b         physical 
b      a         physical 

第 2 步
生成所有可能的组合:

import itertools 
 
c = list(itertools.product(name_list, name_list)) 
c 
 
 
[('a', 'a'), 
 ('a', 'b'), 
 ('a', 'c'), 
 ('b', 'a'), 
 ('b', 'b'), 
 ('b', 'c'), 
 ('c', 'a'), 
 ('c', 'b'), 
 ('c', 'c')] 

第 3 步
索引到您的数据框中,并保存:

df = df.loc[df.index.intersection(c)].reset_index() 
df 
 
  Source Target Interaction 
0      b      a    physical 
1      b      c    physical 
 
df.to_csv('nets.csv') 

如果您有两个或多个 name_list 需要从中查找组合,而不是从单个 name_list 中获取元素,则可以选择此选项,其中情况下,您会选择 MaxU 的答案。