【发布时间】:2022-01-28 01:36:51
【问题描述】:
我正在尝试在 pandas DataFrame 上并行化一个函数,我想知道为什么并行化比单核解决方案慢得多。我知道并行化有其成本......但我很好奇是否有办法改进代码以便并行化更快。
在我的情况下,我有一个用户 ID 列表(300 000(所有字符串)),需要检查用户 ID 是否也存在于另一个仅包含 10 000 个条目的列表中。
由于我无法重现原始代码,所以我给出了一个导致相同性能问题的整数示例:
import pandas as pd
import numpy as np
from joblib import Parallel, delayed
import time
df = pd.DataFrame({'All': np.random.randint(50000, size=300000)})
selection = pd.Series({'selection': np.random.randint(10000, size=10000)}).to_list()
t1=time.perf_counter()
df['Is_in_selection_single']=np.where(np.isin(df['All'], selection),1,0).astype('int8')
t2=time.perf_counter()
print(t2-t1)
def add_column(x):
return(np.where(np.isin(x, selection),1,0))
df['Is_in_selection_parallel'] = Parallel(n_jobs=4)(delayed(add_column)(x) for x in df['All'].to_list())
t3=time.perf_counter()
print(t3-t2)
时间打印结果如下:
0.0307
53.07
这意味着并行化比单核慢 1766 倍。
在我的真实例子中,使用User-Id,单核需要1分钟,但15分钟后并行化还没有完成......
我需要并行化,因为我需要多次执行此操作,因此最终脚本需要几分钟才能运行。 感谢您的任何建议!
【问题讨论】:
-
我认为
np.where是不必要的,因为astype('int8')会将 bool 转换为 int。
标签: python pandas numpy joblib