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

前端 未结 8 1650
清酒与你
清酒与你 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:23

    First, make a categorical series:

    weekdays = pd.Series(['Sun', 'Sun', 'Wed', 'Mon', 'Mon']).astype('category')
    

    Then, inspect its "categories":

    weekdays.cat.categories.get_loc('Sun')
    
    0 讨论(0)
  • 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 ...
    })
    
    0 讨论(0)
  • 2021-02-01 15:32

    Its very simple, they have a built-in function for this.

    from sklearn import preprocessing
    le = preprocessing.LabelEncoder()
    ..
    # your model steps and when you have results
    ..
    
    prediction_decoded = le.inverse_transform(prediction_encoded)
    print(prediction_decoded)
    
    0 讨论(0)
  • 2021-02-01 15:35

    You can create additional dictionary with mapping:

    from sklearn import preprocessing
    le = preprocessing.LabelEncoder()
    le.fit(data['name'])
    le_name_mapping = dict(zip(le.classes_, le.transform(le.classes_)))
    print(le_name_mapping)
    {'Tom': 0, 'Nick': 1, 'Kate': 2}
    
    0 讨论(0)
  • 2021-02-01 15:37

    A simple & elegant way to do the same.

    cat_list = ['Sun', 'Sun', 'Wed', 'Mon', 'Mon']
    encoded_data, mapping_index = pd.Series(cat_list).factorize()
    

    and you are done, check below

    print(encoded_data)
    print(mapping_index)
    print(mapping_index.get_loc("Mon"))
    
    0 讨论(0)
  • 2021-02-01 15:38
    train['cat'] = train['cat'].map(list(train['cat'].value_counts().to_frame().reset_index().reset_index().set_index('index').to_dict().values())[0])
    
    0 讨论(0)
提交回复
热议问题