Pandas convert_to_r_dataframe函数KeyError

时间:2015-02-07 11:17:03

标签: python numpy pandas rpy2

我创建了一个pandas DataFrame:

import pandas as pd

df = pd.DataFrame(x.toarray(), columns = colnames)

然后我将其转换为R数据帧:

import pandas.rpy.common as com

rdf = com.convert_to_r_dataframe(df)

在具有此配置的Windows下,没有问题:

>>> pd.show_versions()

INSTALLED VERSIONS
------------------
commit: None
python: 2.7.7.final.0
python-bits: 32
OS: Windows
OS-release: 7
machine: AMD64
processor: AMD64 Family 16 Model 4
byteorder: little
LC_ALL: None
LANG: None

pandas: 0.14.1
numpy: 1.8.2
rpy2: 2.4.4
...

但是当我使用这种配置在Linux上执行它时:

>>> pd.show_versions()

INSTALLED VERSIONS
------------------
commit: None
python: 2.7.3.final.0
python-bits: 64
OS: Linux
OS-release: 3.2.0-29-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8

pandas: 0.14.1
numpy: 1.8.2
rpy2: 2.4.4
...

我明白了:

Traceback (most recent call last):
  File "app.py", line 232, in <module>
    clf.global_cl(df, df2)
  File "/home/uzer/app/util/clftool.py", line 202, in global_cl
    rdf = com.convert_to_r_dataframe(df)
  File "/home/uzer/app/venv/local/lib/python2.7/site-packages/pandas/rpy/common.py", line 324, in convert_to_r_dataframe
    value = VECTOR_TYPES[value_type](value)
KeyError: <type 'numpy.int64'>

似乎VECTOR_TYPES没有<type 'numpy.int64'>作为关键字。但事实并非如此:

VECTOR_TYPES = {np.float64: robj.FloatVector,
            np.float32: robj.FloatVector,
            np.float: robj.FloatVector,
            np.int: robj.IntVector,
            np.int32: robj.IntVector,
            np.int64: robj.IntVector,
            np.object_: robj.StrVector,
            np.str: robj.StrVector,
            np.bool: robj.BoolVector}

所以我在convert_to_r_dataframe../pandas/rpy/common.py)中打印了变量类型:

for column in df:
    value = df[column]
    value_type = value.dtype.type
    print("value_type: %s") % value_type
    if value_type == np.datetime64:
        value = convert_to_r_posixct(value)
    else:
        value = [item if pd.notnull(item) else NA_TYPES[value_type]
                 for item in value]
        print("Is value_type == np.int64: %s") % (value_type is np.int64)
        value = VECTOR_TYPES[value_type](value)
        ...

这就是结果:

value_type: <type 'numpy.int64'>
Is value_type == np.int64: False

怎么可能?鉴于32位Windows版本没有问题,可能是64位Linux Python版本的问题?

编辑: @lgautier建议,我对此进行了修改:

rdf = com.convert_to_r_dataframe(df)

为:

from rpy2.robjects import pandas2ri
rdf = pandas2ri.pandas2ri(df)

这很有效。

注意:我的数据帧包含utf-8特殊字符,作为列名,以unicode解码。当调用DataFrame构造函数(包含在rpy2/robjects/vectors.py中)时,此行尝试将unicode字符串(包含特殊字符)编码为ascii字符串:

kv = [(str(k), conversion.py2ri(obj[k])) for k in obj]

这会产生错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 4: ordinal not in range(128)

要解决这个问题,我必须改变这一行:

kv = [(k.encode('UTF-8'), conversion.py2ri(obj[k])) for k in obj]

Rpy2应该引入一种允许更改编码的方法。

1 个答案:

答案 0 :(得分:2)

考虑使用rpy2自己的转换(在Linux上似乎与int64一起使用):

# create a test DataFrame
import numpy
import pandas

i2d = numpy.array([[1, 2, 3], [4, 5, 6]], dtype="int64")
colnames = ('a', 'b', 'c')
dataf = pandas.DataFrame(i2d, 
                         columns = colnames)

# rpy2's conversion of pandas objects
from rpy2.robjects import pandas2ri
pandas2ri.activate()

现在pandas DataFrame对象将自动转换 使用嵌入式R在每次调用时使用rpy2 / R DataFrame对象 例如:

from rpy2.robjects.packages import importr
# R's "base" package
base = importr('base')
# call the R function "summary"
print(base.summary(dataf))

也可以明确地调用转换:

from rpy2.robjects import conversion
rpy2_dataf = conversion.py2ro(dataf)

修改(添加自定义以解决str(k)问题)

如果与转换相关的任何内容需要本地定制,则可以相对容易地实现。单程 改变R DataFrame的构建方式是:

import pandas.DataFrame as PandasDataFrame
import rpy2.robjects.vectors.DataFrame as RDataFrame
from rpy2 import rinterface
@conversion.py2ro.register(PandasDataFrame)
def py2ro_pandasdataframe(obj):
    ri_dataf = conversion.py2ri(obj)
    # cast down to an R list (goes through a different code path
    # in the DataFrame constructor, avoiding `str(k)`) 
    ri_list = rinterface.SexpVector(ri_dataf)
    return RDataFrame(ri_list)

从现在开始,上面的转换函数将在大熊猫时使用 DataFrame存在:

rpy2_dataf = conversion.py2ro(dataf)