Last active
May 24, 2019 23:15
-
-
Save sethbunke/c8132a78432ae99a6410ceaaa5f06854 to your computer and use it in GitHub Desktop.
Simple example of creating dummy variables using Python Pandas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import pandas and numpy | |
import pandas as pd | |
import numpy as np | |
#create dataframe with some random data | |
df = pd.DataFrame(np.random.rand(10, 2) * 10, columns=['Price', 'Qty']) | |
#add a column with random string values that would need to have dummy variables created for them | |
df['City'] = [np.random.choice(('Chicago', 'Boston', 'New York')) for i in range(df.shape[0])] | |
#create dummy variables for the column | |
dummies = pd.get_dummies(df['City']) | |
#drop the original column | |
df = df.drop('City', axis=1) | |
#add dummy variables | |
df = df.join(dummies) | |
print(df) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can't believe that I'm writing the first feedback for this post. It really helped me, thanks!