Convert pandas DataFrame Column to Dummy Matrix in Python (Example Code)

In this Python programming tutorial you’ll learn how to create a dummy matrix.

Preparing the Example

import pandas as pd                                        # Import pandas library
my_df = pd.DataFrame({'A':['a', 'b', 'a', 'c', 'b', 'd'],  # Construct example DataFrame
                      'B':range(1, 7),
                      'C':range(7, 1, - 1)})
print(my_df)
#    A  B  C
# 0  a  1  7
# 1  b  2  6
# 2  a  3  5
# 3  c  4  4
# 4  b  5  3
# 5  d  6  2

Example: Create Dummy Matrix Based On pandas DataFrame Column Using get_dummies() Function

my_dummies = pd.get_dummies(my_df['A'])                    # Apply get_dummies function
print(my_dummies)                                          # Print dummy matrix
#    a  b  c  d
# 0  1  0  0  0
# 1  0  1  0  0
# 2  1  0  0  0
# 3  0  0  1  0
# 4  0  1  0  0
# 5  0  0  0  1

Related Articles

Please find some related tutorials on topics such as variables and lists below:

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top