多处理与Concurrent.futures库python(不适用于Google Compute Engine)

问题描述 投票:0回答:1

我正在尝试并行化一个pandas操作,该操作将具有逗号分隔值的数据帧列拆分为2列。正常的pandas操作在我的python实例上大约需要5秒,它直接在该特定列上使用df.str.split。我的数据帧包含200万行,因此我试图降低代码运行时间。

作为第一种并行化的方法,我使用Python的多处理库,创建了与我的实例上可用的CPU核心数相当的池。对于同一问题的第二种方法,我使用concurrent.futures库,提到了4的chunksize。但是,我看到多处理库与正常的pandas操作(5秒)大致相同,而concurrent.futures占用的数量超过了一分钟跑同一条线。

1)Google Compute Engine是否支持这些Python多处理库? 2)为什么并行处理不能在GCP上运行?

提前致谢。以下是示例代码:

import pandas as pd
from multiprocessing import Pool

def split(e):
    return e.split(",")

df =  pd.DataFrame({'XYZ':['CAT,DOG', 
      'CAT,DOG','CAT,DOG']})

pool = Pool(4)
df_new = pd.DataFrame(pool.map(split, df['XYZ'], columns = ['a','b'])
df_new = pd.concat([df, df_new], axis=1)

上面的代码与下面的代码大致相同,这是一个只使用一个核心的普通pandas操作:

df['a'], df['b'] = df['XYZ'].str.split(',',1).str

使用concurrent.futures:

import concurrent.futures
with concurrent.futures.ProcessPoolExecutor() as pool:
     a = pd.DataFrame(pool.map(split, df['XYZ'], chunksize = 4), 
     columns=['a','b'])
print (a)

使用concurrent.futures的上述代码需要花费一分多钟才能在GCP上运行。请注意,我发布的代码只是示例代码。我在项目中使用的数据框有200万行。任何帮助将非常感激!

python-3.x google-cloud-platform multiprocessing google-compute-engine concurrent.futures
1个回答
0
投票

你为什么选择chunksize=4?这非常小,对于200万行,这只会将其分解为500,000次操作。总运行时间可能只需要1/4的时间,但额外的开销可能会比单线程方法花费更长的时间。

我建议使用更大的chunksize。从10,000到200,000的任何地方都可能是合适的,但你应该根据你得到的结果进行一些实验来调整这个。

© www.soinside.com 2019 - 2024. All rights reserved.