v Convert A Numeric Categorical Variable With Patsy - Python

Convert A Numeric Categorical Variable With Patsy

# import modules
import pandas as pd
import patsy
# Create dataframe
raw_data = {'countrycode': [1, 2, 3, 2, 1]} 
df = pd.DataFrame(raw_data, columns = ['countrycode'])
df
countrycode
0 1
1 2
2 3
3 2
4 1
# Convert the countrycode variable into three binary variables
patsy.dmatrix('C(countrycode)-1', df, return_type='dataframe')
C(countrycode)[1] C(countrycode)[2] C(countrycode)[3]
0 1.0 0.0 0.0
1 0.0 1.0 0.0
2 0.0 0.0 1.0
3 0.0 1.0 0.0
4 1.0 0.0 0.0