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

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

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

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    import pandas as pd

    # 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 score_to_numeric(x):
        if x=='strong': return 3
        if x=='normal': return 2
        if x=='weak':   return 1

    # Apply the function to the score variable
    df['score_num'] = df['score'].apply(score_to_numeric)
    print(); print(df)

Kickstarter_Example_77()
************How to convert strings into numerical variables in Python*************

   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  score_num
0        1    1          0  strong          3
1        1    2          1    weak          1
2        1    3          0  normal          2
3        2    1          1    weak          1
4        2    2          0  strong          3


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
1 developer from Cisco
1 developer from HvH
1 developer from KPMG
1 developer from Vodafone
1 developer from Altimetrik
1 developer from Cognizant
1 developer from ICU Medical
1 developer from LTI
1 developer from YASH Technologies
1 developer from ANAC