gpt4 book ai didi

python - 优化超大 csv 文件中的搜索

转载 作者:太空宇宙 更新时间:2023-11-04 09:07:15 25 4
gpt4 key购买 nike

我有一个只有一列的 csv 文件,但有 620 万行,所有行都包含 6 到 20 个字母之间的字符串。一些字符串会出现在重复(或更多)条目中,我想将它们写入一个新的 csv 文件——我猜测应该有大约 100 万个非唯一字符串。就是这样,真的。然而,连续搜索包含 600 万个条目的字典确实需要时间,如果有任何关于如何进行搜索的提示,我将不胜感激。根据我所做的一些计时,到目前为止,我编写的任何脚本都至少需要一周 (!) 才能运行。

第一次尝试:

in_file_1 = open('UniProt Trypsinome (full).csv','r')
in_list_1 = list(csv.reader(in_file_1))
out_file_1 = open('UniProt Non-Unique Reference Trypsinome.csv','w+')
out_file_2 = open('UniProt Unique Trypsin Peptides.csv','w+')
writer_1 = csv.writer(out_file_1)
writer_2 = csv.writer(out_file_2)

# Create trypsinome dictionary construct
ref_dict = {}
for row in range(len(in_list_1)):
ref_dict[row] = in_list_1[row]

# Find unique/non-unique peptides from trypsinome
Peptide_list = []
Uniques = []
for n in range(len(in_list_1)):
Peptide = ref_dict.pop(n)
if Peptide in ref_dict.values(): # Non-unique peptides
Peptide_list.append(Peptide)
else:
Uniques.append(Peptide) # Unique peptides

for m in range(len(Peptide_list)):
Write_list = (str(Peptide_list[m]).replace("'","").replace("[",'').replace("]",''),'')
writer_1.writerow(Write_list)

第二次尝试:

in_file_1 = open('UniProt Trypsinome (full).csv','r')
in_list_1 = list(csv.reader(in_file_1))
out_file_1 = open('UniProt Non-Unique Reference Trypsinome.csv','w+')
writer_1 = csv.writer(out_file_1)

ref_dict = {}
for row in range(len(in_list_1)):
Peptide = in_list_1[row]
if Peptide in ref_dict.values():
write = (in_list_1[row],'')
writer_1.writerow(write)
else:
ref_dict[row] = in_list_1[row]

编辑:这是 csv 文件中的几行:

SELVQK
AKLAEQAER
AKLAEQAERR
LAEQAER
LAEQAERYDDMAAAMK
LAEQAERYDDMAAAMKK
MTMDKSELVQK
YDDMAAAMKAVTEQGHELSNEER
YDDMAAAMKAVTEQGHELSNEERR

最佳答案

用 Numpy 来做。大致:

import numpy as np
column = 42
mat = np.loadtxt("thefile", dtype=[TODO])
uniq = set(np.unique(mat[:,column]))
for row in mat:
if row[column] not in uniq:
print row

您甚至可以使用 numpy.savetxt 和字符数组运算符对输出阶段进行矢量化,但这可能不会产生太大影响。

关于python - 优化超大 csv 文件中的搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19224903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com