问题
How can one pass datetime64[ns] data to R from rpy2? The following simple case:
import pandas as pd
import rpy2.robjects as robjs
from rpy2.robjects import pandas2ri
pandas2ri.activate()
dti = pd.date_range('2018-01-01', periods=3, freq='H')
robjs.r.summary(dti)
fails with a ValueError: ValueError: Unknown numpy array type "datetime64[ns]".
with rpy2 version 3.3.4 and pandas 1.0.5.
回答1:
Instead of passing DatetimeIndex
to R
as you do:
dti = pd.date_range('2018-01-01', periods=3, freq='H')
type(dti)
pandas.core.indexes.datetimes.DatetimeIndex
try to wrap your data into DataFrame
object:
dti = pd.DataFrame({"DatetimeIndex": pd.date_range('2018-01-01', periods=3, freq='H')})
type(dti)
pandas.core.frame.DataFrame
The result is:
robjs.r.summary(dti)
array(['Min. :2018-01-01 00:00:00 ', '1st Qu.:2018-01-01 00:30:00 ',
'Median :2018-01-01 01:00:00 ', 'Mean :2018-01-01 01:00:00 ',
'3rd Qu.:2018-01-01 01:30:00 ', 'Max. :2018-01-01 02:00:00 '],
dtype='<U29')
来源:https://stackoverflow.com/questions/62599909/rpy2-error-with-datetime64ns-pandas-series