2016-08-02 38 views
0

我花了几个小时对Python进行多处理编码。在我读取document上的代码后,我写下了代码。我的计划是在两个全局数据框中一起添加值,并将结果分配给字典。如何使用字典和数据框编写多处理Python代码

from multiprocessing import Process, Manager 
import pandas as pd 
import numpy as np 
import time 

def f(d): 
    for i in C: 
     d[i] = A.loc[i].sum() + B.loc[i].sum() 

C = [10,20,30] 
A = pd.DataFrame(np.matrix('1,2;3,4;5,6'), index = C, columns = ['A','B']) 
B = pd.DataFrame(np.matrix('3,4;5,4;5,2'), index = C, columns = ['A','B']) 

if __name__ == '__main__': 
    manager = Manager() 
    d = manager.dict() 
    d = dict([(c, 0) for c in C]) 
    t0 = time.clock() 
    p = Process(target=f, args=(d,)) 
    p.start() 
    p.join() 
    print time.clock()-t0, 'seconds processing time' 
    print d 

d = dict([(c, 0) for c in C]) 
t0 = time.clock() 
f(d) 
print time.clock()-t0, 'seconds processing time' 
print d 

在我的Linux服务器如下所示,这是不结果我期望:

0.0秒处理时间

{10:0,20:0,30:0}

0.0秒处理时间

{10:10,20:16,30:18}

似乎多处理部分没有将两个数据帧的值加在一起。你们能给我一些提示吗?

在此先感谢。这里

+0

'Process'重复记忆,所以d会有所不同。同时尝试用'threading.Thread'代替 –

+0

,我检查了文档。你几乎是正确的。检查我的回答 –

回答

0

的例子,你能适应和工作原理:

https://docs.python.org/2/library/multiprocessing.html

您必须使用管理对象可以进程之间共享内存。

在您的例子,你创建一个字典使用的经理,但你有一个正常的字典杀死它的行之后

manager = Manager() 
d = manager.dict() # correct 
d = dict([(c, 0) for c in C]) # d is not a manager.dict: no shared memory 

而是做到这一点(测试编译)

d = manager.dict([(c, 0) for c in C]) 
+0

正确的方法是'd = manager.dict([(c,0)for c in C])'。 – Wedoso

+0

我之后添加了它,只是测试它的时间 –