Panda DataFrame上的多处理器



我正在Dataframe列上应用一个函数,但我想让它更快,因为该函数在串行执行时需要大量处理时间。

df[df['codes']=='None']['q'][:1].apply(lambda x: clf(x,candidate_labels))

串行地,一行只需要2.52 secs就可以运行,但当使用多处理运行下面的代码时,51.61 secs2500 rows的处理时间要长得多,所以运行函数需要很多时间。我希望至少在20%上加快速度。

import multiprocessing
import pandas as pd
import numpy as np
def clf(x):
...
return list
def _apply_df(args):
df, func, kwargs = args
return df.apply(func, **kwargs)
def apply_by_multiprocessing(df, func, **kwargs):
workers = kwargs.pop('workers')
pool = multiprocessing.Pool(processes=workers)
result = pool.map(_apply_df, [(d, func, kwargs)
for d in np.array_split(df, workers)])
pool.close()
return pd.concat(list(result))

if __name__ == '__main__':
tart_time = time.time()
res=apply_by_multiprocessing(df[df['codes']=='None']['q'][:1],clf, workers=4)  
print(res)
print("--- %s seconds ---" % (time.time() - start_time))
## run by 4 processors

我也尝试过不同的多处理迭代,但似乎没有一个能加快流程,因为它们会减慢我的代码。

from pandarallel import pandarallel
import time
pandarallel.initialize(progress_bar=True)
start_time = time.time()
categories = df[df['codes']=='None']['q'][:10].parallel_apply(lambda x: clf(x,candidate_labels))
print("--- %s seconds ---" % (time.time() - start_time))

另一个实验:

import multiprocessing as mp
def clf:
...
return list
if __name__ == '__main__':
p = mp.Pool(processes=8)
pool_results = p.map(clf, df[df['codes']=='None']['q'][:1])
p.close()
p.join()

也许你可以使用这个:https://github.com/xieqihui/pandas-multiprocess

pip install pandas-multiprocess
from pandas_multiprocess import multi_process

args = {'workers': 4}
result = multi_process(func=clf, data=df, num_process=8, **args)

相关内容

  • 没有找到相关文章

最新更新