2014-09-12 2 views
1

파이썬 (candv 데이터 프레임)에서 csv 파일을 읽고 R에서 작업하여 파이썬으로 돌아가야합니다. 그런 다음 pandas 데이터 프레임을 R 데이터 프레임에 전달하려면 rpy2를 사용하고 ok 작업 (코드 벨로우즈)을 수행하십시오.Rpy2 : pandas 데이터 프레임이 R에 적합하지 않습니다

<class 'rpy2.robjects.vectors.FloatVector'> 

그러나, 나는 R에 맞게 만들려고 :

from pandas import read_csv, DataFrame 
import pandas.rpy.common as com 
import rpy2.robjects as robjects 

r = robjects.r 
r.library("fitdistrplus") 

df = read_csv('./datos.csv') 
r_df = com.convert_to_r_dataframe(df) 
print(type(r_df)) 

그리고이 출력은

fit2 = r.fitdist(r_df, "weibull") 

그러나 나는이 오류가 :

RRuntimeError: Error in (function (data, distr, method = c("mle", "mme", "qme", "mge"), : 
data must be a numeric vector of length greater than 1 

이 질문에 2 개의 질문이 있습니다.
1_ 내가 뭘 잘못 했니?
2_ 파이썬 데이터 프레임을 R로 전달하는 가장 효율적인 방법은 무엇입니까? 나는이 가져 오기를 참조하기 때문에 : https://mega.co.nz/#!P8MEDSzQ!iQyxt73a5pRvJNOxWeSEaFlsVS7_A1sZCAXkUFBLJa0

을 내가 Ipython 2.1 감사를 사용 from rpy2.robjects.packages import importr

이것은 내가 읽은 데이터입니다!

답변

2

당신은 두 가지 문제가 있습니다. (당신이 fitdist()에 대한 R data.frame를 사용하여 시도하는 경우, 당신은 또한 오류가 발생하는 것입니다.)

이 두 번째로, 팬더 < - 팬더가 제공> RPY2 지원 버그는 (아마도) 숫자 팬더 데이터의 변환 결과입니다 프레임을 문자열/문자 R 데이터 프레임 :

In [27]: r.sapply(r_df, r["class"]) 
Out[27]: 
<StrVector - Python:0x1097757a0/R:0x7fa41c6b0b68> 
[str, str, str, str] 

이것은 좋지 않습니다! 다음 코드는 이러한 오류를 수정합니다.

from pandas import read_csv 
import rpy2.robjects as robjects 

r = robjects.r 
r.library("fitdistrplus") 

# this will read in your csv file as a Series, rather than a DataFrame 
series = read_csv('datos.csv', index_col=0, squeeze=True) 

# do the conversion directly, so that we get an R Vector, rather than a 
# data frame, and we know that it's a numeric type 
r_vec = robjects.FloatVector(series) 

fit2 = r.fitdist(r_vec, "weibull") 
2

귀하의 데이터를 사용해 본적이 없지만, 이와 같은 것이 효과가 있습니다. 당신은 당신이 정말로 벡터를 필요로하는 곳에 데이터 프레임을 사용하려고,

첫째 :

%load_ext rmagic 

from pandas import read_csv 
from rpy2.robjects.packages import importr 

# That import alone is sufficient to switch an automatic 
# conversion of numpy objects into rpy2 objects. 
import rpy2.robjects.numpy2ri 
rpy2.robjects.numpy2ri.activate() 

f = importr('fitdistrplus') 
dfp = read_csv('./test.csv') 
f1 = f.fitdist(dfp.as_matrix(), "weibull") 
print f1 
+0

'as '에'SyntaxError : invalid syntax '이 있습니다. 왜? 감사! –

+0

이 '있는'줄이 나타 납니까? 어떤 버전의 파이썬을 사용하고 있습니까? load_ext는 ipython 매크로입니다. http://ipython.org/ipython-doc/stable/interactive/reference.html 파이썬 만 사용한다면 사용하지 못할 수도 있습니다. –