How to convert Categorical features to Numerical Features in Python?
0

How to convert Categorical features to Numerical Features in Python?

This recipe helps you convert Categorical features to Numerical Features in Python
In [1]:
## How to convert Categorical features to Numerical Features in Python 
def Kickstarter_Example_26():
    print()
    print(format('How to convert Categorical features to Numerical Features in Python',
                 '*^82'))
    import warnings
    warnings.filterwarnings("ignore")

    # Load libraries
    from sklearn import preprocessing
    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'])

    # Fit The Label Encoder
    # Create a label (category) encoder object
    le = preprocessing.LabelEncoder()

    # Fit the encoder to the pandas column
    le.fit(df['score'])

    # View The Labels
    print(); print(list(le.classes_))

    # Transform Categories Into Integers
    # Apply the fitted encoder to the pandas column
    print(); print(le.transform(df['score']))

    # Transform Integers Into Categories
    # Convert some integers into their category names
    print(); print(list(le.inverse_transform([2, 2, 1, 0, 1, 2])))

Kickstarter_Example_26()
*******How to convert Categorical features to Numerical Features in Python********

['normal', 'strong', 'weak']

[1 2 0 2 1]

['weak', 'weak', 'strong', 'normal', 'strong', 'weak']