Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert rpy2 ListVector (rpy2.robjects.vectors.ListVector) to python?

I am using rpy2 to run an auto.arima() model from python. My forecast outputs an object of type rpy2.robjects.vectors.ListVector.

input1:  type(forecast)
output: rpy2.robjects.vectors.ListVector

QUESTION: How do I convert this forecast, in the form of an rpy2.robjects.vectors.ListVector, back into python? Note that I have looked at other posts but the answers seem to be too specific to the question and, regardless, couldn't figure out the answer from them.

Note that this ListVector has the following names:

input: print(forecast.names)
output:   [1] "method"    "model"     "level"     "mean"      "lower"     "upper"    
 [7] "x"         "xname"     "fitted"    "residuals"
like image 857
captain ahab Avatar asked Oct 14 '25 03:10

captain ahab


2 Answers

It is possible to convert back to python using ".rx" to select the vector of interest and then using numpy.array:

arima_mean = np.array(forecast.rx('mean'))

and then to pandas, flatten the numpy array first:

pd.DataFrame({'mean':arima_mean.flatten()} )
like image 173
captain ahab Avatar answered Oct 16 '25 15:10

captain ahab


If you also want the forecast data frame with upper 80% and lower 80% you could use

pd.DataFrame({'forecast':np.array(forecast.rx('mean')).flatten(),
        'lo80':np.array(forecast.rx('lower')[0][:2]),
        'hi80':np.array(forecast.rx('upper')[0][:2])})
like image 38
Rosa Alejandra Avatar answered Oct 16 '25 15:10

Rosa Alejandra