将python中的RDa文件作为pandas数据框读取

时间:2016-10-20 16:49:38

标签: python r pandas dataframe rpy2

我有一个我在R中创建的RDa文件。我想在python上读取这个文件作为pandas数据帧。我有以下代码来做同样的事情:

import rpy2.robjects as robjects
import numpy as np
from rpy2.robjects import pandas2ri
pandas2ri.activate()

# load your file
robjects.r['load']('Data.RDa')

matrix = robjects.r['data']

matrix

我得到以下结果:

R object with classes: ('data.frame',) mapped to:
<DataFrame - Python:0x0CF46F58 / R:0x0ED0F200>
[Float..., Float..., Float..., ..., Float..., Float..., Float...]
  area: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x0CF56A80 / R:0x0F281898>
[NA_real_, NA_real_, NA_real_, ..., NA_real_, NA_real_, NA_real_]
  i: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x0CF68E68 / R:0x0F2B9520>
[NA_real_, NA_real_, NA_real_, ..., NA_real_, NA_real_, NA_real_]
  s: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x0CF68940 / R:0x0F380008>
[NA_real_, NA_real_, NA_real_, ..., NA_real_, NA_real_, NA_real_]
  ...
  upslope_area: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x0D03FDA0 / R:0x0FE87C90>
[NA_real_, NA_real_, NA_real_, ..., 292.256494, NA_real_, NA_real_]
  i: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x0D03FC88 / R:0x0FEBF918>
[331347.500000, 331352.500000, 331357.500000, ..., 332187.500000, 332192.500000, 332197.500000]
  s: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x0D03FE68 / R:0x0FEF75A0>
[4554812.500000, 4554812.500000, 4554812.500000, ..., 4553982.500000, 4553982.500000, 4553982.500000]

如何将其转换为pandas数据框?

1 个答案:

答案 0 :(得分:0)

当从搜索路径中检索第一个带有符号&#39; data&#39;的R对象时,这看起来像是对当前转换的缺失调用。 (简而言之,在做robjects.r["data"]时)。如果还没有rpy2跟踪器,请在rpy2跟踪器上打开一个问题,如果未解决或假设过早解决,则在已打开的问题的注释中发出噪音。

明确调用仅限于代码块的转换规则应该可以轻松解决,并可能有助于确保良好的性能。转换机制提供了便利,但往往以牺牲性能为代价,因为每次在转换的任何一个方向上都会产生数据帧的副本。

以下是:

from rpy2.robjects import default_converter
from rpy2.robjects import pandas2ri
from rpy2.robjects.conversion import localconverter

# use the default conversion rules to which the pandas conversion
# is added
with localconverter(default_converter + pandas2ri.converter) as cv:
    dataf = robjects.r["data"]

这是在doc:http://rpy2.readthedocs.io/en/version_2.8.x/robjects_convert.html#local-conversion-rules