get_dummies() creates one new column per unique value in the target categorical column, with each row getting a positive marker in the column matching its original category and a negative marker everywhere else — this one-hot encoding is necessary because most numeric/statistical algorithms can't work directly with text categories, but can work with these binary indicator columns instead. Passing drop_first=True drops the first category's dummy column, since it can always be inferred from the other columns all being negative, which avoids a redundancy issue, multicollinearity, that matters for certain statistical models like linear regression.
1Understanding pd.get_dummies()
get_dummies() creates one new column per unique value in the target categorical column, with each row getting a positive marker in the column matching its original category and a negative marker everywhere else — this one-hot encoding is necessary because most numeric/statistical algorithms can't work directly with text categories, but can work with these binary indicator columns instead. Passing drop_first=True drops the first category's dummy column, since it can always be inferred from the other columns all being negative, which avoids a redundancy issue, multicollinearity, that matters for certain statistical models like linear regression.
Pass drop_first=True when preparing data specifically for a linear regression or similar model sensitive to multicollinearity — keeping every dummy column, including the redundant one that's always inferable from the others, can cause numerical problems for those specific model types.
import pandas as pd
df = pd.DataFrame({"color": ["red", "blue", "green", "blue"]})
print(pd.get_dummies(df))2Practical Example
Here is a real-world application of pd.get_dummies() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"color": ["red", "blue", "green"]})
print(pd.get_dummies(df, drop_first=True))3Best Practices
Follow these guidelines when working with pd.get_dummies():
1. Use get_dummies() to convert categorical text columns into a numeric form that machine learning models can actually use
2. Pass drop_first=True specifically for models sensitive to multicollinearity, like linear/logistic regression, to avoid the redundant reference category
3. Apply get_dummies() consistently across both training and any new/test data, ensuring the exact same set of dummy columns exists in both, since a category present in one but not the other creates a column mismatch
Tip: Pass drop_first=True when preparing data specifically for a linear regression or similar model sensitive to multicollinearity — keeping every dummy column, including the redundant one that's always inferable from the others, can cause numerical problems for those specific model types.
import pandas as pd
df = pd.DataFrame({"color": ["red", "blue", "green", "blue"]})
print(pd.get_dummies(df))