Pandas - make a column dtype object or Factor

前端 未结 3 1498
北荒
北荒 2020-12-24 05:09

In pandas, how can I convert a column of a DataFrame into dtype object? Or better yet, into a factor? (For those who speak R, in Python, how do I as.factor()?)<

3条回答
  •  孤独总比滥情好
    2020-12-24 05:31

    Factor and Categorical are the same, as far as I know. I think it was initially called Factor, and then changed to Categorical. To convert to Categorical maybe you can use pandas.Categorical.from_array, something like this:

    In [27]: df = pd.DataFrame({'a' : [1, 2, 3, 4, 5], 'b' : ['yes', 'no', 'yes', 'no', 'absent']})
    
    In [28]: df
    Out[28]: 
       a       b
    0  1     yes
    1  2      no
    2  3     yes
    3  4      no
    4  5  absent
    
    In [29]: df['c'] = pd.Categorical.from_array(df.b).labels
    
    In [30]: df
    Out[30]: 
       a       b  c
    0  1     yes  2
    1  2      no  1
    2  3     yes  2
    3  4      no  1
    4  5  absent  0
    

提交回复
热议问题