How to convert categorical variables into numerical variables in Python?
0

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