Python | Pandas.CategoricalDtype()

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.

Parameters-
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



Code:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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'], 
                                                   ordered=False))
   
c = pd.api.types.CategoricalDtype(categories=["a","b","d","c"], ordered=True)
print ("\nType : ", c)

chevron_right


filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right




My Personal Notes arrow_drop_up

Aspire to Inspire before I expire

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.