【发布时间】:2015-04-05 21:31:27
【问题描述】:
我通过 RPy2 在 R 中使用 randomForest 库。我想传回使用caretpredict 方法计算的值并将它们加入原始pandas 数据帧。请参见下面的示例。
import pandas as pd
import numpy as np
import rpy2.robjects as robjects
from rpy2.robjects import pandas2ri
pandas2ri.activate()
r = robjects.r
r.library("randomForest")
r.library("caret")
df = pd.DataFrame(data=np.random.rand(100, 10), columns=["a{}".format(i) for i in range(10)])
df["b"] = ['a' if x < 0.5 else 'b' for x in np.random.sample(size=100)]
train = df.ix[df.a0 < .75]
withheld = df.ix[df.a0 >= .75]
rf = r.randomForest(robjects.Formula('b ~ .'), data=train)
pr = r.predict(rf, withheld)
print pr.rx()
返回
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
a a b b b a a a a b a a a a a b a a a a
Levels: a b
但是join 这个如何与withheld 数据框比较或与原始值进行比较?
我试过这个:
import pandas.rpy.common as com
com.convert_robj(pr)
但这会返回一个字典,其中键是字符串。我想有一个解决方法 withheld.reset_index() 然后将 dict 键转换为整数,然后将两者连接起来,但必须有一个更简单的方法!
【问题讨论】:
标签: python r pandas random-forest rpy2