Skip to main content
 首页 » 编程设计

python之使用具有混合类型列的 rpy2 将 pandas df 转换为 R data.frame

2024年12月31日8qq号

如果我有一个 Pandas 数据框,其中包含一个混合了字符和数字数据的列,例如:

d = {'one' : pd.Series(['cat', 2., 3.], index=['a', 'b', 'c']), 
 'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}  
df = pd.DataFrame(d) 
 
%%R -i df 
str(df) 

然后当使用 rpy2 将其转换为 R data.frame 时,混合列中的每个值在 R data.frame 中被赋予其自己的列,并填充相同的值。上面的代码生成了一个包含 5 列而不是 2 列的 data.frame:

'data.frame':   4 obs. of  5 variables: 
 $ one.a: chr  "cat" "cat" "cat" "cat" 
 $ one.b: num  2 2 2 2 
 $ one.c: num  3 3 3 3 
 $ one.d: num  NaN NaN NaN NaN 
 $ two  : num  1 2 3 4 

这是预期的行为吗?如果是,为什么?

(我正在使用在 Python 3.5.4 |Anaconda 自定义(64 位)| Windows 10 和 rpy2 2.9.1 上运行的 Jupyter notebook 5.0.0)

谢谢。

请您参考如下方法:

看起来 rpy2 正在制作一个 r listvector 而不是 r stringvector。我在转换数据框时遇到了类似的问题,有些列同时具有字符串和 NaN。尽管我使用的是 pandas2ri.py2ri() 而不是 R magic,但我认为它们是相似的。

此代码似乎有效。

# Your code with pandas2ri instead of rmagic 
d = {'one' : pandas.Series(['cat', 2., 3.], index=['a', 'b', 'c']), 
     'two' : pandas.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}  
df = pandas.DataFrame(d) 
 
print(df) 
 
pandas2ri.activate() 
r_df = pandas2ri.py2ri(df) 
print(r_df) 
 
# convert each column individually to see the vector type in R 
r_df1 = pandas2ri.py2ri(df['one']) 
print(type(r_df1)) 
 
r_df2 = pandas2ri.py2ri(df['two']) 
print(type(r_df2)) 
 
# Make an rpy2 OrdDict, be sure to include the None to avoid indexing problems 
od = rlc.OrdDict([('one', robjects.StrVector(['cat', 2., 3., None])), 
                  ('two', robjects.FloatVector([1., 2., 3., 4.]))]) 
 
# make a vector for rownames 
od_rownames = robjects.StrVector(['a', 'b', 'c', 'd']) 
 
# convert the OrdDict to an r dataframe and assign rownames 
od_df = robjects.DataFrame(od) 
print(od_df) 
 
od_df.rownames = od_rownames 
print(od_df) 

更多信息可用https://rpy2.github.io/doc/v2.9.x/html/vector.html#creating-objects