Convert categorical data in pandas dataframe

后端 未结 10 1887
予麋鹿
予麋鹿 2020-11-27 10:01

I have a dataframe with this type of data (too many columns):

col1        int64
col2        int64
col3        category
col4        category
col5        categ         


        
10条回答
  •  清酒与你
    2020-11-27 10:21

    Here multiple columns need to be converted. So, one approach i used is ..

    for col_name in df.columns:
        if(df[col_name].dtype == 'object'):
            df[col_name]= df[col_name].astype('category')
            df[col_name] = df[col_name].cat.codes
    

    This converts all string / object type columns to categorical. Then applies codes to each type of category.

提交回复
热议问题