跳转至

使用 joblib 对 Pandas 数据进行并行处理

本文章向大家介绍使用 joblib 对 Pandas 数据进行并行处理,主要包括使用 joblib 对 Pandas 数据进行并行处理使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

使用 joblib 对 Pandas 数据进行并行处理

如果需要对一个很大的数据集进行操作,而基于一列数据生成新的一列数据可能都需要耗费很长时间。

于是可以使用 joblib 进行并行处理。

假设我们有一个 dataframe 变量 data,要基于它的 source 列生成新的一列 double,其实就是把原来的 source 列做了个平方运算。感觉就这个简单的运算,应该有更简单的方法,在这里只是举个例子,我们使用 apply 方法并行实现。

如果直接使用 apply 那么直接如下实现

1
2
3
4
5
6
import pandas as pd

def double_func(data):
    return pow(data,2)

data["double"] = data["source"].apply(double_func)

使用并行实现如下

import pandas as pd
from joblib import Parallel, delayed

def double_func(data):
    return pow(data,2)

def key_func(subset):
    subset["double"] = subset["source"].apply(double_func)

data_grouped = data.groupby(data.index)
results = Parallel(n_jobs=8)(delayed(key_func)(group) for name, group in data_grouped)
data = pd.concat(results)

基本原理就是把整个 dataframe 根据 index,每行生成了一个子数据集,而把每个子数据集作为子任务使用多进程运行,最终生成 results 是多进程运行生成的结果的 list,使用 concat 重新组合就是我们最终想要的结果了。

n_jobs 参数就是需要使用几个进程池来运行程序。貌似一般 CPU 是几核的用几个进程会比较好?

其实速度并不是成倍减少的,具体原因我也……不太好讲清,但是还是可以很大幅度提升运行速度的。

顺便一提,如果数据集很大,程序一跑起来,根本不知道它跑得怎么样了,还是说卡死了。

注意到,我们生成的 data_grouped 是一个可迭代的对象,那么就可以使用 tqdm 来可视化 进度条

如果在 jupyter 里面使用的话,代码可以是下面这样

import pandas as pd
from joblib import Parallel, delayed
from tqdm import tqdm, tqdm_notebook

tqdm_notebook().pandas()

def double_func(data):
    return pow(data,2)

def key_func(subset):
    subset["double"] = subset["source"].apply(double_func)

data_grouped = data.groupby(data.index)
results = Parallel(n_jobs=8)(delayed(key_func)(group) for name, group in tqdm(data_grouped))
data = pd.concat(results)

友情提示 ,在我自己使用的时候遇到 bug ,提示无法从 Pandas 导入 PanelGroupby 的错误。查了许久才发现,是新版 Pandas 删除了PanelGroupby 这个模块。解决办法其实就是升级 tqdm,在最新版已经修复了这个 bug 了。

原文地址:https://www.cnblogs.com/IvyWong/p/11889926.html

Any text/graphics/videos and other articles on this website that indicate "Source: xxx" are reprinted on this website for the purpose of transmitting more information, which does not mean that we agree with their views or confirm the authenticity of their content. If you are involved in the content of the work, copyright and other issues, please contact this website, we will delete the content in the first time!
Author:
Source: http://www.manongjc.com/detail/13-uevfxkgtfptbcqx.html