I would like to speed up pandas apply function. I have been using swifter . It currently takes about 5 mins for 200000 records using multiprocessing as below . Is there any way to speed this up further .
def partial_match(source_words, dest_words):
matched_words = ''
if any(word in dest_words for word in source_words) :
match_words_list = set(source_words)&set(dest_words)
matched_words = ",".join(match_words_list)
return matched_words
def exact_match(source_words, dest_words):
matched_words = ''
if all(word in dest_words for word in source_words) :
match_words_list = set(source_words)&set(dest_words)
matched_words = ",".join(match_words_list)
return matched_words
series_index = ['match_type', 'matched_words' ]
def perform_match(x):
match_series = pd.Series(np.repeat('', len(series_index)), index = series_index)
if x['remove_bus_ending'] == 'Y':
x['dest_words'] = x['dest_words_2']
else:
x['dest_words'] = x['dest_words_1']
# exact match
if (x['partial_match_flag'] == 'Y') :
match_series['matched_words'] = partial_match(x['source_words'], x['dest_words'])
if match_series['matched_words'] != '':
match_series['match_type'] = 'Partial Match'
elif (x['exact_match_2'] == 'Y'):
match_series['matched_words'] = exact_match(x['source_words'], x['dest_words'])
if match_series['matched_words'] != '':
match_series['match_type'] = 'Exact Match'
return match_series
from multiprocessing import Pool
from functools import partial
import numpy as np
def parallelize(data, func, num_of_processes=8):
data_split = np.array_split(data, num_of_processes)
pool = Pool(num_of_processes)
data = pd.concat(pool.map(func, data_split))
pool.close()
pool.join()
return data
def run_on_subset(func, data_subset):
return data_subset.swifter.apply(func, axis=1)
def parallelize_on_rows(data, func, num_of_processes=8):
return parallelize(data, partial(run_on_subset, func), num_of_processes)
df[match_series] = parallelize_on_rows(df, perform_match)
below is some sample data
flag1 partial_match_flag exact_match_flag source_words dest_word_2 dest_words_1
0 N Y N [song, la] [urban, karamay, credit, city, co, kunlun, com... [ltd, urban, karamay, credit, city, co, kunlun...
1 N Y N [song, la] [al, abdulah, nasser] [al, abdulah, nasser]
2 N Y N [song, la] [al, abdulah, nasser] [al, abdulah, nasser]
3 N Y N [song, la] [abdulamir, mahdi] [abdulamir, mahdi]
4 N Y N [song, la] [abdullah, al, nasser] [abdullah, al, nasser]
5 N Y N [song, la] [abu, al, jud] [abu, al, jud]
6 N Y N [song, la] [al, herz, adam] [al, herz, adam]