Skip to main content
 首页 » 编程设计

python之带有 rpy2 和多处理的 Pandas

2025年05月04日16emanlee

我正在尝试使用 Pandas 和 R 来加速进程。

假设我有以下数据框:

import pandas as pd 
from random import randint 
df = pd.DataFrame({'mpg': [randint(1, 9) for x in xrange(10)], 
                   'wt': [randint(1, 9)*10 for x in xrange(10)], 
                   'cyl': [randint(1, 9)*100 for x in xrange(10)]}) 
df 
  mpg wt  cyl 
0  3  40  100 
1  6  30  200 
2  7  70  800 
3  3  50  200 
4  7  50  400 
5  4  10  400 
6  3  70  500 
7  8  30  200 
8  3  40  800 
9  6  60  200 

然后,我使用 rpy2 对一些数据建模:

import rpy2.robjects.packages as rpackages 
import rpy2.robjects as robjects 
from rpy2.robjects import pandas2ri 
pandas2ri.activate() 
 
base = rpackages.importr('base') 
stats = rpackages.importr('stats') 
 
formula = 'mpg ~ wt + cyl' 
fit_full = stats.lm(formula, data=df) 

在此之后我做了一些预测:

rfits = stats.predict(fit_full, newdata=df) 

此代码对于小数据帧运行没有问题,但实际上我有一个包含数百万行的大数据帧,我试图使用其他 rpy2 模型加速预测部分,但不幸的是这需要很长时间来处理。

我第一次尝试使用多处理库来完成这项任务但没有成功:

import multiprocessing as mp 
 
pool = mp.Pool(processes=4) 
rfits = pool.map(predict(fit_full, newdata=df)) 

但可能我做错了什么,因为我看不到任何速度提升。

我认为这里的主要问题是因为我试图将 pool.map 应用于 rpy2 函数而不是 Python 预定义函数。可能有一些不使用多处理库的变通解决方案,但我看不到任何解决方案。

如有任何帮助,我们将不胜感激。提前致谢。

请您参考如下方法:

您是否尝试过使用 StatsModels?

Fitting models using R-style formulas Since version 0.5.0, statsmodels allows users to fit statistical models using R-style formulas. Internally, statsmodels uses the patsy package to convert formulas and data to the matrices that are used in model fitting. The formula framework is quite powerful; this tutorial only scratches the surface. A full description of the formula language can be found in the patsy docs

import statsmodels.formula.api as smf 
 
formula = 'mpg ~ wt + cyl' 
model = smf.ols(formula=formula, data=df) 
params = model.fit().params 
 
>>> params 
params 
Intercept    5.752803 
wt           0.037770 
cyl         -0.004112 
 
>>> model.predict(params, exog=df) 
array([ 1725.83759267,  2876.50148582,   575.25352613,  1150.6605447 , 
        1150.51281171,  3451.54178359,   575.53800931,   575.4146529 , 
        2876.58372342,  5177.46831077])