How to convert string categorical variables into numerical variables using Label Encoder?

How to convert string categorical variables into numerical variables using Label Encoder?

This recipe helps you convert string categorical variables into numerical variables using Label Encoder
In [1]:
## How to convert string categorical variables into numerical variables using Label Encoder
def Kickstarter_Example_78():
    print()
    print(format('How to convert strings into numerical variables using Label Encoder','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    import pandas as pd
    from sklearn.preprocessing import LabelEncoder

    # Create dataframe
    raw_data = {'patient': [1, 1, 1, 2, 2],
                'obs': [1, 2, 3, 1, 2],
                'treatment': [0, 1, 0, 1, 0],
                'score': ['strong', 'weak', 'normal', 'weak', 'strong']}

    df = pd.DataFrame(raw_data, columns = ['patient', 'obs', 'treatment', 'score'])
    print(); print(df)

    # Create a function that converts all values of df['score'] into numbers
    def dummyEncode(df):
          columnsToEncode = list(df.select_dtypes(include=['category','object']))
          le = LabelEncoder()
          for feature in columnsToEncode:
              try:
                  df[feature] = le.fit_transform(df[feature])
              except:
                  print('Error encoding '+feature)
          return df
    df = dummyEncode(df)

    print(); print(df)

Kickstarter_Example_78()
*******How to convert strings into numerical variables using Label Encoder********

   patient  obs  treatment   score
0        1    1          0  strong
1        1    2          1    weak
2        1    3          0  normal
3        2    1          1    weak
4        2    2          0  strong

   patient  obs  treatment  score
0        1    1          0      1
1        1    2          1      2
2        1    3          0      0
3        2    1          1      2
4        2    2          0      1


Stuck at work?
Can't find the recipe you are looking for. Let us know and we will find an expert to create the recipe for you. Click here
Companies using this Recipe
2 developers from Infosys
1 developer from KPMG
1 developer from Thomson Reuters
1 developer from Cognizant
1 developer from Huawei
1 developer from LTI
1 developer from Vodafone
1 developer from Altimetrik
1 developer from Embicon
1 developer from HvH