Python导入RDS文件转DataFrame报错求助
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.
- First install the library via pip:
pip install pyreadr
- 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

