Python | Pandas.CategoricalDtype ()

NumPy | Python Methods and Functions

pandas.api.types.CategoricalDtype (Categories = None, Ordered = None): This class is useful for specifying a value independent Category Data type with categories and order.

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

Return- Type specification for categorical data

Code :

# Python code explaining
# numpy.pandas.CategoricalDtype ()

 
# import 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 ( "b:" , b)

 

print ( "True / False:" , a = = CategoricalDtype ([ `a` , `b` , ` c` ] , 

ordered = False ))

  

c = pd.api.types.CategoricalDtype (categories = [ "a" , "b" , "d" , "c" ], ordered = True )

print ( "Type:" , c)

c1 = pd. Series ([ `a` , ` b` , `a` , ` e` ], dtype = c)

print ( "c1:" , c1)

 

 

c2 = pd.DataFrame ({ ` A` : list ( `abca` ), ` B` : list ( `bccd` )})

 

c3 = CategoricalDtype (categories = list ( ` abcd` ), ordered = True )

 

c4 = c2.astype (c3)

 

print ( "c4 [` A`]: " , c4 [ `A` ])





Get Solution for free from DataCamp guru