Pandas dataframe applymap并行执行
Pandas dataframe applymap parallel execution
我有以下函数可以将一堆正则表达式应用于数据框中的每个元素。我应用正则表达式的数据框是一个 5MB 的块。
def apply_all_regexes(data, regexes):
# find all regex matches is applied to the pandas' dataframe
new_df = data.applymap(
partial(apply_re_to_cell, regexes))
return regex_applied
def apply_re_to_cell(regexes, cell):
cell = str(cell)
regex_matches = []
for regex in regexes:
regex_matches.extend(re.findall(regex, cell))
return regex_matches
由于 applymap
的串行执行,处理所花费的时间为 ~ elements * (serial execution of the regexes for 1 element)
。无论如何调用并行性?我尝试了 ProcessPoolExecutor
,但这似乎比串行执行花费的时间更长。
您是否尝试过将一个大数据帧拆分为线程数小的数据帧,并行应用正则表达式映射并将每个小的 df 重新组合在一起?
我能够对有关基因表达的数据框做类似的事情。
如果你得到预期的输出,我会 运行 它小规模和控制。
很遗憾,我没有足够的声誉来发表评论
def parallelize_dataframe(df, func):
df_split = np.array_split(df, num_partitions)
pool = Pool(num_cores)
for x in df_split:
print(x.shape)
df = pd.concat(pool.map(func, df_split))
pool.close()
pool.join()
return df
这是我用的一般函数
我有以下函数可以将一堆正则表达式应用于数据框中的每个元素。我应用正则表达式的数据框是一个 5MB 的块。
def apply_all_regexes(data, regexes):
# find all regex matches is applied to the pandas' dataframe
new_df = data.applymap(
partial(apply_re_to_cell, regexes))
return regex_applied
def apply_re_to_cell(regexes, cell):
cell = str(cell)
regex_matches = []
for regex in regexes:
regex_matches.extend(re.findall(regex, cell))
return regex_matches
由于 applymap
的串行执行,处理所花费的时间为 ~ elements * (serial execution of the regexes for 1 element)
。无论如何调用并行性?我尝试了 ProcessPoolExecutor
,但这似乎比串行执行花费的时间更长。
您是否尝试过将一个大数据帧拆分为线程数小的数据帧,并行应用正则表达式映射并将每个小的 df 重新组合在一起?
我能够对有关基因表达的数据框做类似的事情。 如果你得到预期的输出,我会 运行 它小规模和控制。
很遗憾,我没有足够的声誉来发表评论
def parallelize_dataframe(df, func):
df_split = np.array_split(df, num_partitions)
pool = Pool(num_cores)
for x in df_split:
print(x.shape)
df = pd.concat(pool.map(func, df_split))
pool.close()
pool.join()
return df
这是我用的一般函数