使用rpy2通过R函数传递pandas数据帧

时间:2016-12-04 08:31:18

标签: python r pandas dataframe rpy2

我正在尝试用Python重现R结果。以下R代码有效:

@Repository
public interface SupplierBillRepository extends JpaRepository<SupplierBill, Integer> {
    @Query(value = "SELECT SB.bill_id, SB.date, SB.supplier_id,  SUM(SBD.quantity * SBD.rate) as bill_amount,  COALESCE((SELECT SUM(SBPD.payment_amount) FROM table_supplier_bill_payment_details SBPD WHERE SBD.bill_id = SBPD.bill_id ),0.00) as paid_amount from table_supplier_bills SB INNER JOIN table_supplier_bill_details SBD ON SB.bill_id = SBD.bill_id WHERE SB.supplier_id = ?1 group by SBD.bill_id ORDER BY SB.bill_id DESC" , nativeQuery = true)
    List< SupplierBillResults> getSupplierBillResults(Integer sid);
}

但不是以下Python代码:

library("TTR")
library("zoo")
library("xts")
library("quantmod")
getSymbols("^GSPC",from = "2014-01-01", to = "2015-01-01")
dataf = GSPC[,c("GSPC.High", "GSPC.Low", "GSPC.Close")]
result = CCI(dataf, n=20, c=0.015)

使用TTR.CCI时,我在最后一行发生错误。返回的回溯和错误是:

from datetime import datetime
from rpy2.robjects.packages import importr
TTR = importr('TTR')
import pandas_datareader as pdr
from rpy2.robjects import pandas2ri
pandas2ri.activate()

GSPC = pdr.get_data_yahoo(symbols='^GSPC', start=datetime(2014, 1, 1), end=datetime(2015, 1, 1))
dataf = GSPC[['High', 'Low', 'Close']]
result = TTR.CCI(dataf, n=20, c=0.015)

1 个答案:

答案 0 :(得分:0)

R代码中的data.frame实际上是一个“xts”“zoo”对象,你只需要在python代码中将它转换成一个:

rzoo = importr('zoo')
datazoo = zoo.as_zoo_xts(dataf)
result = TTR.CCI(datazoo, n=20, c=0.015)