Pandas - make a column dtype object or Factor

前端 未结 3 1503
北荒
北荒 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:27

    You can use the astype method to cast a Series (one column):

    df['col_name'] = df['col_name'].astype(object)
    

    Or the entire DataFrame:

    df = df.astype(object)
    

    Update

    Since version 0.15, you can use the category datatype in a Series/column:

    df['col_name'] = df['col_name'].astype('category')
    

    Note: pd.Factor was been deprecated and has been removed in favor of pd.Categorical.

提交回复
热议问题