簡體   English   中英

Python:在多處理進程之間共享大型數據幀

[英]Python: Sharing large dataframes between multiprocessing process

我是 Python 和多處理的新手。 我必須將 2 個大型 xml(大約 6GB)文件解析為 2 個數據幀。 這兩個文件都可以獨立處理。

就我在 Python 中學到的而言,我可以通過多處理來做到這一點。 所以流程 1 解析 xml1 文件並將其加載到數據幀 流程 2 解析 xml2 文件並將其加載到數據幀

現在我想將進程 1 生成的數據幀用於進程 2 誰能告訴我哪種方法是實現它的最佳方法? 我主要關心的是在進程之間共享數據幀。

問候 Vipul

您使用多個進程主要是因為您想並行讀取數據。 一旦它被讀入,似乎沒有什么理由讓你繼續兩個過程。 即您的進程應該讀取數據,然后終止並讓主進程繼續。

但是,我建議使用multi-threading而不是multi-processing 差異並不總是很明顯,但multi-threading將使在主線程和子線程之間共享全局變量變得更簡單(我將在下面解釋)。 多線程的另一個優點是,如果單個線程失敗,它不會導致整個應用程序崩潰。 多處理不是這種情況。 在此處查看更多信息: http : //net-informations.com/python/iq/multi.htm

需要一些時間來習慣 Python 中並行的工作方式,您必須注意的主要考慮因素之一是如何確保您所做的事情是線程安全的。 通常用於將數據傳入和傳出線程的機制是隊列。 這確保在任何給定時間只有一個線程訪問同一個對象。

話雖這么說,在你的簡單的例子,你可以簡單地定義兩個全局變量和啟動兩個線程,每個數據讀入的這些全局變量(即跨線程沒有共享的變量)。 您還必須告訴主線程等待兩個線程都完成后再繼續,否則主線程可能會在子線程仍在處理數據時嘗試訪問數據。 (同樣,通常您會采用基於隊列的策略來避免這個問題,但在這里不一定需要)。

下面是一些示例代碼:

import threading
import pandas as pd
import time

def get_df_1():
    #set the scope of the variable to "global", meaning editing it here, it is edited globally
    global df_1 

    # read in your xml file here (for the example I simply create some dummy data)
    data = [['tom', 10], ['nick', 15], ['juli', 14]]
    df_1 = pd.DataFrame(data, columns=['Name', 'Age'])

    # wait five seconds (for illustration purposes to simulate  working time)
    time.sleep(5)
    print("df_1 fetched")

def get_df_2():
    global df_2
    data = [['tom', 176], ['nick', 182], ['juli', 167]]
    df_2 = pd.DataFrame(data, columns=['Name', 'Height'])
    time.sleep(5)
    print("df_2 fetched")

df_1 = None
df_2 = None

#define threads
t1 = threading.Thread(target=get_df_1)
t2 = threading.Thread(target=get_df_2)

# start threads
t1.start()
t2.start()

#this will print immediately
print("Threads have been started")

# wait until threads finish
t1.join()
t2.join()

#this will only print after the threads are done
print("Threads have finished")

print(df_1)
print(df_2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM