Convert column to categorical in pandas python

Categorical function is used to convert / typecast integer or character column to categorical in pandas python. Typecast a numeric column to categorical using categorical function(). Convert a character column to categorical in pandas   Let’s see how to

  • Typecast column to categorical in pandas python using categorical() function
  • Convert column to categorical in pandas using astype() function

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'])

df1

so the resultant dataframe will be

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

 

The current data type of columns is

# Get current data type of columns
df1.dtypes

Convert column to categorical in pandas python 1

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

 

 

Method 1:

Convert column to categorical in pandas python using categorical() function

## Typecast to Categorical column in pandas

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

now it has been converted to categorical which is shown below

Convert column to categorical in pandas python 2

 

Method 2:

Convert column to categorical in pandas python using astype() function

as.type() function takes ‘category’ as argument and converts the column to categorical in pandas as shown below.

## Typecast to Categorical column in pandas

df1['Is_Male'] = df1.Is_Male.astype('category')
df1.dtypes

as.type() function converts “Is_Male” column to categorical which is shown below

Convert column to categorical in pandas python 2


Other Related Topics:

for further details on categorical() function one can refer this documentation

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

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.