How to convert categorical variables in Python to a factor variable in R? (Reticulate)

Viewed 422

I'm using reticulate to convert a python saved .pkl into an R dataframe. I see the categorical python type is kept in the R dataframe. I'm guessing R doesn't know how to deal with python categorical variables. How do I convert those into factor variables in R?

#Looking at the class of some of the variables in the R dataframe, I get

class(df$variable)

$variable
[1] "pandas.core.arrays.categorical.Categorical" 
"pandas.core.arrays.base.ExtensionArray"    
[3] "pandas.core.base.PandasObject"              
"pandas.core.base.StringMixin"              
[5] "pandas.core.accessor.DirNamesMixin"         "python.builtin.object"      

#I get the right levels, but this doesn't seem to be R-friendly 

> table(levels(factor(as.character(df$varibale))))

[level 1, level 2, level 3, level 4, level 5, ..., NaN, NaN, NaN, NaN, 
NaN]\nLength: 464121\nCategories (6, object): [level 1 < level 2 < level 3 
< level 4 < level 5 < level 6] 
0 Answers
Related