You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python导入RDS文件转DataFrame报错求助

Fixing RDS Import Error When Transitioning from R to Python

Hey there! Since you're making the switch from R to Python and hitting a roadblock reading your RDS file with rpy2, let's sort this out together. That TypeError about the categories parameter is a common hiccup when converting R factors to pandas objects via rpy2—here are two solid solutions:

Option 1: Use pyreadr (The Simpler Route)

rpy2 can be finicky with R-specific data types like factors, which is likely causing your error. pyreadr is a purpose-built library for reading R files (including RDS) directly into pandas DataFrames, skipping the rpy2 conversion headaches entirely.

  1. First install the library via pip:
pip install pyreadr
  1. Then read your RDS file with just a few lines of code:
import pyreadr

# Read the RDS file; returns a dict of objects stored in the file
result = pyreadr.read_r('clus_resf.rds')

# Extract your DataFrame (assuming it's the only object in the RDS)
df = result[next(iter(result.keys()))]

This method handles factor-to-categorical conversions smoothly, so you won't run into that categories type mismatch error.

Option 2: Fix the rpy2 Conversion Workflow

If you'd rather stick with rpy2, the issue comes from the global pandas2ri.activate() not properly converting R's StrSexpVector (used for factor levels) into a list-like object pandas expects. Here's how to adjust your code:

import rpy2.robjects as robjects
from rpy2.robjects import pandas2ri
from rpy2.robjects.conversion import localconverter
import pandas as pd

# Load the RDS file into an R object
readRDS = robjects.r['readRDS']
r_df = readRDS('clus_resf.rds')

# Use a local converter for more controlled R-to-Python conversion
with localconverter(robjects.default_converter + pandas2ri.converter):
    df = robjects.conversion.rpy2py(r_df)

# Manually handle any remaining factor columns if needed
for col in df.columns:
    if isinstance(df[col].values, robjects.vectors.StrVector):
        df[col] = pd.Categorical(df[col])

By using localconverter instead of activating pandas2ri globally, you avoid the automatic conversion misstep that triggered your error. The manual check ensures any leftover R factor vectors get properly turned into pandas categoricals.

Quick Breakdown of the Original Error

Your code failed because rpy2's pandas2ri was trying to convert an R factor's levels (stored as a StrSexpVector) into a pandas categorical, but pandas expects a standard list-like type instead of R's specialized vector. The fixes above either bypass this issue entirely or adjust the conversion logic to play nice with R's data structures.

内容的提问来源于stack exchange,提问作者Seyed Omid Nabavi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:06:09