简体   繁体   中英

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"

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()} )

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])})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM