Rpy2(使用数据帧)如何解决Python(NaN)和R(NA)的冲突?

2024-06-01 00:30:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据帧:result,有两列。你知道吗

doy(一年中的第几天:自变量,值1,2,3,….365)。你知道吗

bookings(因变量,279个数值和86个NaN值)

请在下面找到数据帧的一部分:

enter image description here

我的目标是使用R (randomForest::rfImpute)对缺失值进行插补,以便进行进一步的光谱分析。 因此,我使用rpy2在Python脚本中使用R代码。我已经导入了必要的包/库。我还激活了“pandas2ri”。你知道吗

import random
import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
base = importr('base')
utils = importr('utils')

randomForest = importr('randomForest')

from rpy2.robjects import pandas2ri
pandas2ri.activate()


r_df = pandas2ri.py2ri(result)

type(r_df)
print(r_df.head())
print(base.summary(r_df))


random.seed(222)

result.imputed = randomForest.rfImpute('bookings', 'doy', data = r_df)`

但是每当我运行代码时,我都会得到错误:No NA values found in bookings.

很明显,R代码无法解释丢失的值。你知道吗

我还尝试替换R数据帧r_df中的NaN with NA

robjects.r('r_df[is.nan(as.numeric(r_df))] = NA')

但是当我运行代码时,我得到了错误:object r_df is not found.

有办法解决这个问题吗?到目前为止,我有点卡住了,似乎找不到有用的文档。你知道吗

请在下面找到一些单独代码行的其他输出。你知道吗

enter image description here

enter image description here

enter image description here


Tags: 数据代码importdfbaseresultnanna
1条回答
网友
1楼 · 发布于 2024-06-01 00:30:05

(…)

robjects.r('r_df[is.nan(as.numeric(r_df))] = NA')

but when I run the code, I get the error: object r_df is not found.

r_df是Python变量的名称(在Python代码中定义的名称),因此embedded R不知道它。你知道吗

Is there a way around this issue? As of now, I am a bit stuck and can't seem to find a helpful documentation.

这个呢: https://rpy2.github.io/doc/v2.9.x/html/robjects_rinstance.html#r-the-instance-of-r

相关问题 更多 >