带rpy2和多处理的Pandas

2024-10-03 15:28:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用熊猫和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对一些数据进行建模:

^{pr2}$

在这之后,我做了一些预测:

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预定义的函数。可能有一些不使用多处理库的解决方案,但是我看不到任何解决方案。在

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


Tags: 数据inimportdfforaspdpool
1条回答
网友
1楼 · 发布于 2024-10-03 15:28:22

你试过使用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])

相关问题 更多 >