How to convert categorical variables into numerical variables in Python?

How to convert categorical variables into numerical variables in Python?

This recipe helps you convert categorical variables into numerical variables in Python
In [1]:
## How to convert categorical variables into numerical variables in Python
def Kickstarter_Example_76():
    print()
    print(format('How to convert categorical variables into numerical variables in Python','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    import pandas as pd

    # Create a dataframe
    data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
                'last_name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze'],
                'gender': ['male', 'female', 'male', 'female', 'female']}

    df = pd.DataFrame(data, columns = ['first_name', 'last_name', 'gender'])
    print(); print(df)

    # Create a set of dummy variables from the gender variable
    df_gender = pd.get_dummies(df['gender'])

    # Join the dummy variables to the main dataframe
    df_new = pd.concat([df, df_gender], axis=1)
    print(); print(df_new)

    # Alterative for joining the new columns
    df_new = df.join(df_gender)
    print(); print(df_new)

Kickstarter_Example_76()
*****How to convert categorical variables into numerical variables in Python******

  first_name last_name  gender
0      Jason    Miller    male
1      Molly  Jacobson  female
2       Tina       Ali    male
3       Jake    Milner  female
4        Amy     Cooze  female

  first_name last_name  gender  female  male
0      Jason    Miller    male       0     1
1      Molly  Jacobson  female       1     0
2       Tina       Ali    male       0     1
3       Jake    Milner  female       1     0
4        Amy     Cooze  female       1     0

  first_name last_name  gender  female  male
0      Jason    Miller    male       0     1
1      Molly  Jacobson  female       1     0
2       Tina       Ali    male       0     1
3       Jake    Milner  female       1     0
4        Amy     Cooze  female       1     0


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 Capgemini
1 developer from EXL Service
1 developer from ICU Medical
1 developer from Megasoft
1 developer from Vodafone
1 developer from Altimetrik
1 developer from CareSource
1 developer from Godrej And Boyce
1 developer from MudraCircle