2017-12-08 12 views
0

나는 수십만 개의 행이있는 pandas DataFrame을 가지고 있으며, 그 DataFrame의 여러 열에 병렬로 많은 시간이 걸리는 함수를 적용하려고합니다.pandas DataFrame의 여러 열을 병렬로 함수에 적용하는 방법

나는 함수를 순차적으로 적용하는 법을 알고있다. 예를 들어 :

import hashlib 

import pandas as pd 


df = pd.DataFrame(
    {'col1': range(100_000), 'col2': range(100_000, 200_000)}, 
    columns=['col1', 'col2']) 


def foo(col1, col2): 
    # This function is actually much more time consuming in real life 
    return hashlib.md5(f'{col1}-{col2}'.encode('utf-8')).hexdigest() 


df['md5'] = df.apply(lambda row: foo(row.col1, row.col2), axis=1) 

df.head() 
# Out[5]: 
# col1 col2        md5 
# 0  0 100000 92e2a2c7a6b7e3ee70a1c5a5f2eafd13 
# 1  1 100001 01d14f5020a8ba2715cbad51fd4c503d 
# 2  2 100002 c0e01b86d0a219cd71d43c3cc074e323 
# 3  3 100003 d94e31d899d51bc00512938fc190d4f6 
# 4  4 100004 7710d81dc7ded13326530df02f8f8300 

하지만, 어떻게 내 컴퓨터에서 사용 가능한 모든 코어를 활용, 기능 foo 병렬을 적용 할 것인가?

답변

1

가장 쉬운 방법은 concurrent.futures입니다. 각 프로세스는 한 번에 1000 행 (즉 만 1000 개의 행마다 프로세스를 초기화의 오버 헤드를 지불 할 것이다) 처리 때문에 chunksize=1_000 지정

import concurrent.futures 

with concurrent.futures.ProcessPoolExecutor(16) as pool: 
    df['md5'] = list(pool.map(foo, df['col1'], df['col2'], chunksize=1_000)) 

df.head() 
# Out[10]: 
# col1 col2        md5 
# 0  0 100000 92e2a2c7a6b7e3ee70a1c5a5f2eafd13 
# 1  1 100001 01d14f5020a8ba2715cbad51fd4c503d 
# 2  2 100002 c0e01b86d0a219cd71d43c3cc074e323 
# 3  3 100003 d94e31d899d51bc00512938fc190d4f6 
# 4  4 100004 7710d81dc7ded13326530df02f8f8300 

빨리이 실행합니다.

파이썬 3.2 이상에서만 작동합니다.

관련 문제