Skip to content
Related Articles

Related Articles

Improve Article

Python | Pandas.CategoricalDtype()

  • Last Updated : 21 Sep, 2018

pandas.api.types.CategoricalDtype(categories = None, ordered = None) : This class is useful for specifying the type of Categorical data independent of the values, with categories and orderness.

categories : [index like] Unique categorisation of the categories.
ordered : [boolean] If false, then the categorical is treated as unordered.

Return- Type specification for categorical data


# Python code explaining 
# numpy.pandas.CategoricalDtype()
# importing libraries
import numpy as np
import pandas as pd
from pandas.api.types import CategoricalDtype
a = CategoricalDtype(['a', 'b', 'c'], ordered=True)
print ("a : ", a)
b = CategoricalDtype(['a', 'b', 'c'])
print ("\nb : ", b)
print ("\nTrue / False : ", a == CategoricalDtype(['a', 'b', 'c'], 
c = pd.api.types.CategoricalDtype(categories=["a","b","d","c"], ordered=True)
print ("\nType : ", c)

c1 = pd.Series(['a', 'b', 'a', 'e'], dtype = c)
print ("c1 : \n", c1)
c2 = pd.DataFrame({'A': list('abca'), 'B': list('bccd')})
c3 = CategoricalDtype(categories=list('abcd'), ordered=True)
c4 = c2.astype(c3)
print ("\n c4['A'] : \n", c4['A'])

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :