我在Dataframe列上应用了一个函数,但是我想使其变得更快,因为该函数在串行完成时会占用大量处理时间。
df[df['codes']=='None']['q'][:1].apply(lambda x: clf(x,candidate_labels))
通常,单行只需要2.52 secs
来运行,但是使用多处理来运行下面的代码时,它需要花费更长的时间51.61 secs
,而我大约需要2500 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()
答案 0 :(得分:0)
也许您可以使用此功能: 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)