2015-02-05 5 views
2

RPy2을 통해 R에서 randomForest 라이브러리를 사용하고 있습니다. caretpredict 메서드를 사용하여 계산 된 값을 다시 전달하고 원래 pandas 데이터 프레임에 조인하고 싶습니다. 아래 예를 참조하십시오.Rpy2 및 Pandas : 예측 결과를 팬더 데이터 프레임에 합치십시오

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 

를 반환하지만 어떻게 원래의 값으로 withheld dataframe이를 join 또는 비교할 수

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() 

?

import pandas.rpy.common as com 
com.convert_robj(pr) 

을하지만이 키가 문자열 사전을 반환

나는이 시도했다. 나는 withheld.reset_index()의 주위에 일이 있고 그 후에 dict 열쇠를 정수로 개조하고 그 후에 2 개를 결합한다 그러나 간단한 방법이어야한다다는 것을 짐작한다!

답변

3

팬더에게 a pull-request that adds R factor to Pandas Categorical functionality 이 있습니다. 아직 판다 스 마스터 브랜치에 합병되지 않았습니다. 이 경우,

pr을 팬더 범주로 변환합니다.

def convert_factor(obj): 
    """ 
    Taken from jseabold's PR: https://github.com/pydata/pandas/pull/9187 
    """ 
    ordered = r["is.ordered"](obj)[0] 
    categories = list(obj.levels) 
    codes = np.asarray(obj) - 1 # zero-based indexing 
    values = pd.Categorical.from_codes(codes, categories=categories, 
             ordered=ordered) 
    return values 
예를 들어

, 기능 predict에 의해 반환

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") 

def convert_factor(obj): 
    """ 
    Taken from jseabold's PR: https://github.com/pydata/pandas/pull/9187 
    """ 
    ordered = r["is.ordered"](obj)[0] 
    categories = list(obj.levels) 
    codes = np.asarray(obj) - 1 # zero-based indexing 
    values = pd.Categorical.from_codes(codes, categories=categories, 
             ordered=ordered) 
    return values 


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 = convert_factor(r.predict(rf, withheld)) 

withheld['pr'] = pr 
print(withheld) 
1

는 R 객체 pr 당신이 생각 할 수있는 "벡터"입니다 : 는 그 때까지, 당신은 해결 방법으로 사용할 수 있습니다 파이썬 array.array 또는 numpy 일차원 배열로.

pr의 요소 순서가 withheld의 행과 일치한다는 점에서 "결합"은 필요하지 않습니다. 하나는 (Adding new column to existing DataFrame in Python pandas 참조) withheld 에 추가 열로 pr을 추가해야합니다 : 기본적으로

withheld['predictions'] = pd.Series(pr, 
            index=withheld.index) 

이 정수의 열을 추가합니다 (R 인자는 정수로 인코딩되어 있기 때문에). 하나는 단순히 (http://rpy.sourceforge.net/rpy2/doc-2.5/html/robjects_convert.html 참조) RPY2의 변환을 사용자 정의 할 수 있습니다

참고 : RPY2의 버전 2.6.0을 판다 Categorical 벡터의 처리를 포함, 불필요한 설명 컨버터의 사용자 정의 만들기.

robjects.conversion.ri2py(pr) 

당신은 결과를 추가하기로 결정 수에 R 요인이있을 때마다이와

@robjects.conversion.ri2py.register(robjects.rinterface.SexpVector) 
def ri2py_vector(vector): 
    # based on 
    # https://bitbucket.org/rpy2/rpy2/src/a75413b09852991869332da615fa754923c32039/rpy/robjects/pandas2ri.py?at=default#cl-73 

    # special case for factors 
    if 'factor' in vector.rclass: 
     res = pd.Categorical.from_codes(np.asarray(vector) - 1, 
             categories = vector.do_slot('levels'), 
             ordered = 'ordered' in vector.rclass) 
    else: 
     # use the numpy converter first 
     res = numpy2ri.ri2py(obj) 
    if isinstance(res, recarray): 
     res = PandasDataFrame.from_records(res) 
    return res 

, 비 RPY2 객체에 어떤 RPY2 객체의 변환은 팬더 Categorical를 반환한다 이 마지막 전환을 데이터 표로

비 rpy2 개체로의 변환은 명시 적이어야합니다 (변환기를 호출하는 중 하나임). ipython을 사용하는 경우 암시 적으로 이것을 만들 수있는 방법이 있습니다. https://gist.github.com/lgautier/e2e8709776e0e0e93b8d (및 원래 스레드 https://bitbucket.org/rpy2/rpy2/issue/230/rmagic-specific-conversion).

관련 문제