在Python中使用多進程快速處理資料

來源:互聯網
上載者:User

標籤:art   檔案處理   返回   mat   獲得   unique   false   RoCE   建立   

轉自:78786648

 

資料分區:可以將資料分區處理的任務適合用多進程代碼處理,核心思路是將data分區,對每一片資料處理返回結果(可能是無序的),然後合并。應用情境:多進程爬蟲,類mapreduce任務。缺點是子進程會拷貝父進程所有狀態,記憶體浪費嚴重。

import mathfrom multiprocessing import Pooldef run(data, index, size):  # data 傳入資料,index 資料分區索引,size進程數    size = math.ceil(len(data) / size)    start = size * index    end = (index + 1) * size if (index + 1) * size < len(data) else len(data)    temp_data = data[start:end]    # do something    return data  # 可以返回資料,在後面收集起來processor = 40res = []p = Pool(processor)for i in range(processor):    res.append(p.apply_async(run, args=(data, i, processor,)))    print(str(i) + ‘ processor started !‘)p.close()p.join()for i in res:    print(i.get())  # 使用get獲得多進程處理的結果

 

 

分檔案處理:當記憶體受限時,不能再繼續使用資料分區,因為子進程會拷貝父進程的所有狀態,導致記憶體的浪費。這時候可以考慮先把大檔案分區儲存到磁碟,然後del 釋放掉資料,接著在多進程處理的函數裡面分別讀取,這樣子進程就會分別讀取需要處理的資料,而不會佔用大量記憶體。

 

from multiprocessing import Poolimport pandas as pdimport mathdata=pd.DataFrame({‘user_id‘:[1,2,3,4],‘item_id‘:[6,7,8,9]})users=pd.DataFrame(data[‘user_id‘].unique(),columns=[‘user_id‘])processor=4p=Pool(processor)l_data = len(users)size = math.ceil(l_data / processor)res = []def run(i):    data=pd.read_csv(‘../data/user_‘+str(i)+‘.csv‘)    #todoreturn datafor i in range(processor):    start = size * i    end = (i + 1) * size if (i + 1) * size < l_data else l_data    user = users[start:end]    t_data = pd.merge(data, user, on=‘user_id‘).reset_index(drop=True)    t_data.to_csv(‘../data/user_‘+str(i)+‘.csv‘,index=False)    print(len(t_data))del data,l_data,usersfor i in range(processor):    res.append(p.apply_async(run, args=(i,)))    print(str(i) + ‘ processor started !‘)p.close()p.join()data = pd.concat([i.get() for i in res])

  

 

多進程資料共用:當需要修改共用的資料時,那麼這個時候可以使用資料共用:

from multiprocessing import Process, Manager# 每個子進程執行的函數# 參數中,傳遞了一個用於多進程之間資料共用的特殊字典def func(i, d):    d[i] = i + 100    print(d.values())# 在主進程中建立特殊字典m = Manager()d = m.dict()for i in range(5):    # 讓子進程去修改主進程的特殊字典    p = Process(target=func, args=(i, d))    p.start()p.join()------------[100][100, 101][100, 101, 102, 103][100, 101, 102, 103][100, 101, 102, 103, 104]

  

在Python中使用多進程快速處理資料

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.