Creating dummy variables in pandas for python

Viewed 166261

I'm trying to create a series of dummy variables from a categorical variable using pandas in python. I've come across the get_dummies function, but whenever I try to call it I receive an error that the name is not defined.

Any thoughts or other ways to create the dummy variables would be appreciated.

EDIT: Since others seem to be coming across this, the get_dummies function in pandas now works perfectly fine. This means the following should work:

import pandas as pd

dummies = pd.get_dummies(df['Category'])

See http://blog.yhathq.com/posts/logistic-regression-and-python.html for further information.

11 Answers

A very simple approach without using get_dummies if you have very less categorical variable using NumPy and Pandas.

let, i have a column named <"State"> and it have 3 categorical variable <'New York'>, <'California'> and <'Florida'> and we want to assign 0 and 1 for respectively.

we can do it with following simple code.

import numpy as np
import pandas as pd

dataset['NewYork_State'] = np.where(dataset['State']=='New York', 1, 0)
dataset['California_State'] = np.where(dataset['State']=='California', 1, 0)
dataset['Florida_State'] = np.where(dataset['State']=='Florida', 1, 0)
 

Above we create Three New Columns for storing values "NewYork_State", "California_State", "Florida_State".

Drop the original column

dataset.drop(columns=['State'],axis=1,inplace=True)

A simple and robust way to create dummies based on a column with your category values:

for category in list(df['category_column'].unique()):
    df[category] = lis(map(lambda x: 1 if x==category else 0, df['category_column']))

But watch out when doing some OLS regression because you will need to exclude one of the categorys so you dont fall on dummie trap variable

Related