脚本基本上是根据他们借用的书籍(代码)来衡量学生之间的关系。所以我使用ete2包为不同类型的书建立了一棵树。现在我试图编写一段代码,它从树和一个csv文件中获取数据,并通过函数关系进行一些数据分析.csv文件包含超过50,000行。问题是需要很长时间才能运行代码(大约7天),而它只使用我的计算机CPU和内存的10%到20%。花费太长时间来运行python脚本
这是我用过的CSV文件的一个例子:
ID Code Count
1 A1... 6
1 A2... 5
2 A.... 4
2 D.... 1
2 A1... 2
3 D.... 5
3 D1... 3
3 D2... 5
下面是代码:
from ete2 import Tree
import pandas as pd
import numpy as np
from __future__ import division
import math
data= pd.read_csv('data.csv', names=['ID','Code', 'Count'])
codes_list= list (set(data['Code']))
total_codes= data.shape[0]
students_list= list (set(data['ID']))
####################################
# generate the tree
t = Tree (".....;", format =0)
for i in codes_list:
if '....' in i:
node = t.search_nodes(name = '.....')
node[0].add_child(name= i)
for i in codes_list:
if '...' in i and '....' not in i:
if i[0]+'....' in codes_list:
node = t.search_nodes(name = i[0]+'....')
node[0].add_child(name= i)
else:
node = t.search_nodes(name = '.....')
node[0].add_child(name= i)
# save the tree in a file
t.write(outfile= file_path + "Codes_tree.nh", format =3)
return t.get_ascii(show_internal=True)
####################################
def relationship(code1,code2):
code1_ancestors= t.search_nodes(name=code1)[0].get_ancestors()
code2_ancestors=t.search_nodes(name=code2)[0].get_ancestors(
common_ancestors = []
for a1 in code1_ancestors:
for a2 in code2_ancestors:
if a1==a2:
common_ancestors.append(a1)
IC_values = []
for ca in common_ancestors:
code_descendants=[]
for gd in ca.get_descendants():
code_descendants.append(gd.name)
code_descendants.append(ca)
frequency= 0
for k in code_descendants:
frequency= frequency + code_count.Count[k]
IC = - (math.log (frequency/float (total_codes)))
IC_values.append (IC)
IC_max= max(IC_values)
return IC_max
##################
relationship_matrix = pd.DataFrame(index=[students_list], columns=[students_list])
for student in students_list:
p1= list (self.data.Code[data.ID==student])
for student1 in students_list:
p2= list data.Code[data.PID==student1])
student_l=[]
for l in p1:
for m in p2:
student_l.append(relationship(l,m))
max_score = np.max(np.array(student_l).astype(np.float))
relationship_matrix.loc[student,student1] = max_score
print relationship_matrix
这些编辑真正的帮助,我已经做了,其余不变。尽管它减少了处理时间,但仍需要很长时间才能运行。为什么它不使用所有的内存资源!为什么只有15%? – goodX
也许这就是它需要的所有内存?顺便说一下,当你说CPU使用率是指单核CPU使用率还是一般系统负载?还有一些提示。使用'timeit'来识别代码的缓慢部分。另外,在我看来,您可以并行批处理csv文件,然后将结果合并在一起。看看['multiprocessing'](https://docs.python.org/2/library/multiprocessing.html)。并且不要忘记投票/接受答案,如果它有助于解决你的问题:)。 –