Python - Convert Pandas DataFrame to binary data


Use the get_dummies() method to convert categorical DataFrame to binary data. Following is our Pandas DataFrame with 2 columns −

dataFrame = pd.DataFrame(
   {
      "Student": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'],"Result": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass']
   }
)

Use the get_dummies() and set the column which you want to convert to binary form. Here, we want the Result in “Pass” and “Fail” form to be visible. Therefore, we will set the “Result” column −

pd.get_dummies(dataFrame["Result"]

Example

Following is the code −

import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Student": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'],"Result": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass']
   }
)

print"DataFrame ...\n",dataFrame

# converting to binary data
dfBinary = pd.get_dummies(dataFrame["Result"])
print"\nDisplaying DataFrame in Binary form...\n",dfBinary

Output

This will produce the following output −

DataFrame ...
   Result   Student
0    Pass      Jack
1    Fail     Robin
2    Fail       Ted
3    Pass  Scarlett
4    Pass       Kat

Displaying DataFrame in Binary form...
   Fail   Pass
0     0     1
1     1     0
2     1     0
3     0     1
4     0     1

Updated on: 20-Sep-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements