Convert column to categorical in pandas python

Categorical function is used to convert integer or character column to categorical in pandas python. Let’s see how to

  • Convert column to categorical in pandas python

First let’s create the dataframe


import pandas as pd
import numpy as np

#Create a DataFrame
df1 = {
    'Name':['George','Andrea','micheal','maggie','Ravi',
               'Xien','Jalpa'],
   'Is_Male':[1,0,1,0,1,1,0]}

df1 = pd.DataFrame(df1,columns=['Name','Is_Male'])

print(df1)

so the resultant dataframe will be

Convert-to-categorical-in-pandas-python-1

 

The current data type of columns is


print (df1.dtypes)

Convert-to-categorical-in-pandas-python-2

Data type of  Is_Male column  is integer . so let’s convert it into categorical.

 

 


df1['Is_Male'] = pd.Categorical(df1.Is_Male)
print (df1.dtypes)

now it has been converted to categorical which is shown below

Convert-to-categorical-in-pandas-python-2

 

Convert column to categorical in pandas python                                                                                                                Convert column to categorical in pandas python n