如何使用字典和数据框编写多处理 python 代码

How to write multiprocessing python codes with dictionary and dataframe

我在 Python 上花了几个小时进行多处理编码。在我阅读 document 上的代码后,我在下面编写了代码。我的计划是将两个全局数据框中的值相加,并将结果分配给字典。

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 seconds processing time

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

0.0 seconds processing time

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

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

提前致谢。

此处的示例您可以改编并且有效:

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])