如何用dictionary和datafram编写多处理python代码

2024-04-20 02:16:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我花了几个小时在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}

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

提前谢谢。你知道吗


Tags: 数据代码inimportfortimenpprocess
1条回答
网友
1楼 · 发布于 2024-04-20 02:16:20

这里有一个例子,你可以适应和工作:

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

相关问题 更多 >