2017-01-16 88 views
1

我有多个使用python Pandas库处理的数据文件。每个文件都被逐一处理,并且当我查看任务管理器时,只有一个逻辑处理器被使用(它在〜95%,其余在5%以内)使用多个内核同时处理多个数据文件

有没有办法同时处理数据文件? 如果是这样,有没有办法利用其他逻辑处理器来做到这一点?

(编辑欢迎)

+0

[关于并发视频的思考](https://www.youtube.com/watch?v=Bv25Dwe84g0) – wwii

+1

看看[multipro cessing.pool](https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing.pool) – swenzel

+0

@swenzel击败了我。打算输入确切的东西 –

回答

0

您可以处理在不同的线程或者不同进程中不同的文件。

蟒蛇的好处是,它的框架提供的工具,你要做到这一点:

from multiprocessing import Process 

def process_panda(filename): 
    # this function will be started in a different process 
    process_panda_import() 
    write_results() 

if __name__ == '__main__': 
    p1 = Process(target=process_panda, args=('file1',)) 
    # start process 1 
    p1.start() 
    p2 = Process(target=process_panda, args=('file2',)) 
    # starts process 2 
    p2.start() 
    # waits if process 2 is finished 
    p2.join() 
    # waits if process 1 is finished 
    p1.join() 

程序将启动2子流程,可以用来做处理您的文件。 你可以使用线程做类似的工作。

您可以在这里找到的文档: https://docs.python.org/2/library/multiprocessing.html

这里:

https://pymotw.com/2/threading/

+2

快速注意:它看起来像Python线程不会使用多个核心,根据:http://stackoverflow.com/questions/7542957/is-python-capable-of-running-on-多内核。不过,'multiprocessing'库会使用它。 – phss

+0

伟大的信息,感谢您分享! – KimKulling

+1

@KimKulling,坦克你的代码和额外的链接:) –

0

如果你的文件名列表中,你可以使用此代码:

from multiprocessing import Process 

def YourCode(filename, otherdata): 
    # Do your stuff 

if __name__ == '__main__': 
    #Post process files in parallel 
    ListOfFilenames = ['file1','file2', ..., 'file1000'] 
    ListOfProcesses = [] 
    Processors = 20 # n of processors you want to use 
    #Divide the list of files in 'n of processors' Parts 
    Parts = [ListOfFilenames[i:i + Processors] for i in xrange(0, len(ListOfFilenames), Processors)] 

    for part in Parts: 
     for f in part: 
      p = multiprocessing.Process(target=YourCode, args=(f, otherdata)) 
      p.start() 
      ListOfProcesses.append(p) 
     for p in ListOfProcesses: 
      p.join() 
+2

看看'concurrent.futures.ProcessPoolExecutor' - 同样的想法,但仔细地插手,并与角落案件等 - https:// docs .python.org/3/library/concurrent.futures.html – jsbueno

+0

谢谢!但是,不幸的是,它似乎不适用于Python 2.7 ... – Diego

+0

Python 2.7现在已经有七年了 - 它在发布时已经有点老了,因为Python 3已经成熟了。 OP没有提到他在使用Python2。 (当然,一个建议concurrent.futures的答案不得不提到它只是Python 3) – jsbueno