Convert categorical data in pandas dataframe

后端 未结 10 1896
予麋鹿
予麋鹿 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:22

    For a certain column, if you don't care about the ordering, use this

    df['col1_num'] = df['col1'].apply(lambda x: np.where(df['col1'].unique()==x)[0][0])
    

    If you care about the ordering, specify them as a list and use this

    df['col1_num'] = df['col1'].apply(lambda x: ['first', 'second', 'third'].index(x))
    

提交回复
热议问题