2017-05-25 5 views
0

私は2つの列を持つ単純なデータフレームを持っています。 「件名」列内のすべてのレコードに対してデータフレーム列の '関数適用'を自動的にマルチ処理する

+---------+-------+ | subject | score | 
+---------+-------+ | wow  | 0  | 
+---------+-------+ | cool | 0  | 
+---------+-------+ | hey  | 0  | 
+---------+-------+ | there | 0  | 
+---------+-------+ | come on | 0  | 
+---------+-------+ | welcome | 0  | 
+---------+-------+ 

、私は関数を呼び出すと、列「スコア」で結果を更新しています:それはプロセスとして期待通り

df['score'] = df['subject'].apply(find_score) 

Here find_score is a function, which processes strings and returns a score : 

def find_score (row): 
    # Imports the Google Cloud client library 
    from google.cloud import language 

    # Instantiates a client 
    language_client = language.Client() 

    import re 
    pre_text = re.sub('<[^>]*>', '', row) 
    text = re.sub(r'[^\w]', ' ', pre_text) 

    document = language_client.document_from_text(text) 

    # Detects the sentiment of the text 
    sentiment = document.analyze_sentiment().sentiment 

    print("Sentiment score - %f " % sentiment.score) 

    return sentiment.score 

これは正常に動作しますが、その非常に遅く1つ1つレコード。

方法はありますか?これは並列化できますか?手動でデータフレームを小さなチャンクに分割する必要はありませんか?それを自動的に行うライブラリはありますか? language.Client

乾杯

+0

find_score funcのdefを表示できますか? – Allen

+0

daskの使用を検討する – Boud

+0

@Allen質問に関数defを追加しました – gnanagurus

答えて

3

インスタンス化あなたがfind_score関数を呼び出すたびにそう大きなボトルネックとなっています。あなたは、関数のすべての使用のための新しいクライアントのインスタンスを作成する必要があるので、あなたはそれを呼び出す前に、関数外で作成してみません:

# Instantiates a client 
language_client = language.Client() 

def find_score (row): 
    # Imports the Google Cloud client library 
    from google.cloud import language 


    import re 
    pre_text = re.sub('<[^>]*>', '', row) 
    text = re.sub(r'[^\w]', ' ', pre_text) 

    document = language_client.document_from_text(text) 

    # Detects the sentiment of the text 
    sentiment = document.analyze_sentiment().sentiment 

    print("Sentiment score - %f " % sentiment.score) 

    return sentiment.score 

df['score'] = df['subject'].apply(find_score) 

あなたが主張する場合、あなたはこのようにマルチプロセッシング使用することができます。

from multiprocessing import Pool 
# <Define functions and datasets here> 
pool = Pool(processes = 8) # or some number of your choice 
df['score'] = pool.map(find_score, df['subject']) 
pool.terminate() 
関連する問題