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

时间:2017-11-05 14:20:24

标签: python pandas dataframe

我有一个名为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列表对非常慢。有什么建议可以改善这个吗?

2 个答案:

答案 0 :(得分:3)

IIUC :(非常感谢@cᴏʟᴅsᴘᴇᴇᴅ和@Bharath指出错误!)

pointer-events: none

演示:

res = df.loc[df['Source'].isin(name_list) & df['Target'].isin(name_list)]
res.to_csv(...)

答案 1 :(得分:3)

你实际上已经到了一半。很多人对MaxU表示感谢,从他的帖子中借用数据。

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

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's答案。