12 python numpy ipython rpy2 pandas
我想使用pandas进行所有分析以及numpy,但是使用Rpy2来绘制我的数据.我想使用pandas数据帧进行所有分析,然后通过rpy2使用R的完整绘图来绘制这些.py2,我正在使用ipython绘图.这样做的正确方法是什么?
我尝试的几乎所有命令都失败了.例如:
df.我想要df在x/y轴上使用的标签就像在R数据帧中使用一样.有没有办法做到这一点?当我尝试这样做时r.plot,我得到了这个胡言乱语的情节:In: r.plot(df.a, df.b) # df is pandas DataFrame
收益率:
Out: rpy2.rinterface.NULL
导致情节:

正如您所看到的,轴标签是乱七八糟的,它不是像DataFrame那样读取轴标签(X轴是列a,dfY轴是列b).
如果我尝试使用直方图r.hist,它根本不起作用,产生错误:
In: r.hist(df.a)
Out:
...
vectors.pyc in <genexpr>((x,))
293 if l < 7:
294 s = '[' + \
--> 295 ', '.join((p_str(x, max_width = math.floor(52 / l)) for x in self[ : 8])) +\
296 ']'
297 else:
vectors.pyc in p_str(x, max_width)
287 res = x
288 else:
--> 289 res = "%s..." % (str(x[ : (max_width - 3)]))
290 return res
291
TypeError: slice indices must be integers or None or have an __index__ method
Run Code Online (Sandbox Code Playgroud)并导致这个情节:

知道错误是什么意思吗?而且在这里,轴都被搞砸了,乱七八糟的数据.
编辑:只有在使用ipython时才会出现此错误.当我从脚本运行命令时,它仍然会产生有问题的绘图,但至少运行时没有错误.从ipython调用这些命令肯定有问题.
我还尝试将pandas DataFrame转换为dfR DataFrame,如下面的海报所推荐的那样,但是这个错误也失败了:
com.convert_to_r_dataframe(mydf) # mydf is a pandas DataFrame
----> 1 com.convert_to_r_dataframe(mydf)
in convert_to_r_dataframe(df, strings_as_factors)
275 # FIXME: This doesn't handle MultiIndex
276
--> 277 for column in df:
278 value = df[column]
279 value_type = value.dtype.type
TypeError: iteration over non-sequence
Run Code Online (Sandbox Code Playgroud)如何使用这些基本的绘图功能来处理Pandas DataFrame(从Pandas DataFrame的标签中读取图表的标签),还可以在Pandas DF到R DF之间进行转换?
EDIT2:这是一个完整的csv文件"test.txt"(http://pastebin.ca/2311928)以及我的代码来回答@dale的评论:
import rpy2
from rpy2.robjects import r
import rpy2.robjects.numpy2ri
import pandas.rpy.common as com
from rpy2.robjects.packages import importr
from rpy2.robjects.lib import grid
from rpy2.robjects.lib import ggplot2
rpy2.robjects.numpy2ri.activate()
from numpy import *
import scipy
# load up pandas df
import pandas
data = pandas.read_table("./test.txt")
# plotting a column fails
print "data.c2: ", data.c2
r.plot(data.c2)
# Conversion and then plotting also fails
r_df = com.convert_to_r_dataframe(data)
r.plot(r_df)
Run Code Online (Sandbox Code Playgroud)
绘制"data.c2"列的调用失败,即使data.c2是pandas df的列,因此对于所有意图和目的应该是一个numpy数组.我使用activate()调用,所以我认为它将把这个列作为一个numpy数组处理并绘制它.
data转换为R数据帧后绘制数据帧的第二次调用也会失败.这是为什么?如果我test.txt从R作为数据帧加载,我能够plot(),因为我的数据帧从pandas转换为R,看起来它也应该在这里工作.
当我尝试rmagicipython时,由于某些原因,它不会启动绘图窗口,尽管它不会出错.即如果我这样做:
In [12]: X = np.array([0,1,2,3,4])
In [13]: Y = np.array([3,5,4,6,7])
In [14]: import rpy2
In [15]: from rpy2.robjects import r
In [16]: import rpy2.robjects.numpy2ri
In [17]: import pandas.rpy.common as com
In [18]: from rpy2.robjects.packages import importr
In [19]: from rpy2.robjects.lib import grid
In [20]: from rpy2.robjects.lib import ggplot2
In [21]: rpy2.robjects.numpy2ri.activate()
In [22]: from numpy import *
In [23]: import scipy
In [24]: r.assign("x", X)
Out[24]:
<Array - Python:0x592ad88 / R:0x6110850>
[ 0, 1, 2, 3, 4]
In [25]: r.assign("y", Y)
<Array - Python:0x592f5f0 / R:0x61109b8>
[ 3, 5, 4, 6, 7]
In [27]: %R plot(x,y)
Run Code Online (Sandbox Code Playgroud)
没有错误,但也没有绘图窗口.无论如何,我想坚持使用rpy2而不是依靠rpy2 rmagic.
谢谢.
[注意:你在"编辑2"中的代码在这里工作(Python 2.7,rpy2-2.3.2,R-1.15.2).
正如@dale提到的那样,每当R对象是匿名的(对象不存在R符号)时,R deparse(substitute())将最终返回structure()R对象,并且可能的修复是指定"xlab"和"ylab"参数; 对于某些情节,您还必须指定main(标题).
解决这个问题的另一种方法是使用R的公式并提供数据框(下面,我们计算出转换部分之后).
忘掉里面的东西pandas.rpy.它既破碎又似乎忽略了rpy2中可用的功能.
使用ipython进行转换的早期快速修复可以很容易地转换为正确的转换.我正在考虑在rpy2代码库中添加一个(带有更多铃声和口哨声),但同时只需在代码示例中的所有导入后添加以下代码段.无论何时进行R调用,它都会透明地将pandas的DataFrame对象转换为rpy2 DataFrame.
from collections import OrderedDict
py2ri_orig = rpy2.robjects.conversion.py2ri
def conversion_pydataframe(obj):
if isinstance(obj, pandas.core.frame.DataFrame):
od = OrderedDict()
for name, values in obj.iteritems():
if values.dtype.kind == 'O':
od[name] = rpy2.robjects.vectors.StrVector(values)
else:
od[name] = rpy2.robjects.conversion.py2ri(values)
return rpy2.robjects.vectors.DataFrame(od)
elif isinstance(obj, pandas.core.series.Series):
# converted as a numpy array
res = py2ri_orig(obj)
# "index" is equivalent to "names" in R
if obj.ndim == 1:
res.names = ListVector({'x': ro.conversion.py2ri(obj.index)})
else:
res.dimnames = ListVector(ro.conversion.py2ri(obj.index))
return res
else:
return py2ri_orig(obj)
rpy2.robjects.conversion.py2ri = conversion_pydataframe
Run Code Online (Sandbox Code Playgroud)
现在,以下代码将"正常工作":
r.plot(rpy2.robjects.Formula('c3~c2'), data)
# `data` was converted to an rpy2 data.frame on the fly
# and the a scatter plot c3 vs c2 (with "c2" and "c3" the labels on
# the "x" axis and "y" axis).
Run Code Online (Sandbox Code Playgroud)
我还注意到你正在导入ggplot2,而不使用它.目前,必须明确要求转换.例如:
p = ggplot2.ggplot(rpy2.robjects.conversion.py2ri(data)) +\
ggplot2.geom_histogram(ggplot2.aes_string(x = 'c3'))
p.plot()
Run Code Online (Sandbox Code Playgroud)
调用r.plot函数时,需要显式传入标签.
r.plot([1,2,3],[1,2,3], xlab="X", ylab="Y")
Run Code Online (Sandbox Code Playgroud)
当您在R中绘图时,它会抓取标签,通过deparse(substitute(x))该标签从中获取变量名称plot(testX, testY).当你通过rpy2传入python对象时,它是一个匿名的R对象,类似于R中的以下内容:
> deparse(substitute(c(1,2,3)))
[1] "c(1, 2, 3)"
Run Code Online (Sandbox Code Playgroud)
这就是为什么你会得到疯狂的标签.
很多时候,使用rpy2 只来回推送数据是比较理想的.
r.assign('testX', df.A)
r.assign('testY', df.B)
%R plot(testX, testY)
rdf = com.convert_to_r_dataframe(df)
r.assign('bob', rdf)
%R plot(bob$$A, bob$$B)
Run Code Online (Sandbox Code Playgroud)
http://nbviewer.ipython.org/4734581/
使用rpy.转换是大熊猫的一部分,所以你不需要做yoursef http://pandas.pydata.org/pandas-docs/dev/r_interface.html
In [1217]: from pandas import DataFrame
In [1218]: df = DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C':[7,8,9]},
......: index=["one", "two", "three"])
......:
In [1219]: r_dataframe = com.convert_to_r_dataframe(df)
In [1220]: print type(r_dataframe)
<class 'rpy2.robjects.vectors.DataFrame'>
Run Code Online (Sandbox Code Playgroud)