Any way to get mappings of a label encoder in Python pandas?

前端 未结 8 1877
清酒与你
清酒与你 2021-02-01 15:11

I am converting strings to categorical values in my dataset using the following piece of code.

data[\'weekday\'] = pd.Categorical.from_array(data.weekday).labels         


        
8条回答
  •  别跟我提以往
    2021-02-01 15:26

    There are many ways of doing this. You can consider pd.factorize, sklearn.preprocessing.LabelEncoder etc. However, in this specific case, you have two options which will suit you best:

    Going by your own method, you can add the categories:

    pd.Categorical( df.weekday, [ 
        'Sunday', 'Monday', 'Tuesday', 
        'Wednesday', 'Thursday', 'Friday', 
        'Saturday']  ).labels
    

    The other option is to map values directly using a dict

    df.weekday.map({
        'Sunday': 0,
        'Monday': 1,
         # ... and so on. You get the idea ...
    })
    

提交回复
热议问题