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
The current data type of columns is
# Get current data type of columns df1.dtypes
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
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
Other Related Topics:
- Get the data type of column in pandas python
- Check and Count Missing values in pandas python.
- Convert numeric column to character in pandas python (integer to string)
- Convert character column to numeric in pandas python (string to integer)
- Extract first n characters from left of column in pandas python
- Extract last n characters from right of the column in pandas python
- Replace a substring of a column in pandas python
for further details on categorical() function one can refer this documentation