Pandas CategoricalIndex function remove_categories() in Python
The Pandas CategoricalIndex function remove_categories() used to remove the specified categories. It must be an old (existing) categories. It returns Categorical by replacing specified removal elements with NaN.
Note : If the removals categories are not included in the CategoricalIndex, it will raise a ValueError.
Syntax
 1 CategoricalIndex.remove_categories(*args, **kwargs)
removals : It can be either category or list of categories which should be removed which will be replaced with NaN.
remove_categories() function
 1 import pandas as pd
 2 
 3 index = pd.CategoricalIndex(['x', 'y', 'z', 'y'])
 4 print('The CategoricalIndex object :')
 5 print(index)
 6 
 7 res = index.remove_categories(['y', 'z'])
 8 print('The removed categories :')
 9 print(res)
In the above example, a CategoricalIndex object is created by passing an array. A remove_categories() function is called by passing an array of categories. It replace the specified categories with NaN and returns a Categorical object that assigned to the variable that will be printed on console.
Output
 1 The CategoricalIndex object :
 2 CategoricalIndex(['x', 'y', 'z', 'y'],
 3  categories=['x', 'y', 'z'], ordered=False, dtype='category')
 4 
 5 The removed categories :
 6 CategoricalIndex(['x', nan, nan, nan],
 7  categories=['x'], ordered=False, dtype='category')

remove_categories() with non existing categories

remove_categories() with non existing categories
 1 import pandas as pd
 2 
 3 index = pd.CategoricalIndex(['x', 'y', 'z', 'y'])
 4 print('The CategoricalIndex object :')
 5 print(index)
 6 
 7 res = index.remove_categories(['a', 'z'])
 8 print('The removed categories :')
 9 print(res)
In the above example, a remove_categories() function is called by passing an array of categories which are not old categories that raise ValueError.
Output
 1 raise ValueError(f"removals must all be in old categories: {not_included}")
 2 ValueError: removals must all be in old categories: {'a'}

Example 2

Example 2
 1 import pandas as pd
 2 
 3 index = pd.CategoricalIndex([1, 2, 1, 3])
 4 
 5 print('The CategoricalIndex object :')
 6 print(index)
 7 
 8 res = index.remove_categories([1])
 9 print('The removed categories :')
 10 print(res)
In the above example, a CategoricalIndex object is created by passing an array of numbers. A remove_categories() function is called by passing an array of categories. It replace the specified categories with NaN and returns a Categorical object that assigned to the variable that will be print.
Output
 1 The CategoricalIndex object :
 2 CategoricalIndex([1, 2, 1, 3], categories=[1, 2, 3],
 3               ordered=False, dtype='category')
 4 
 5 The removed categories :
 6 CategoricalIndex([nan, 2, nan, 3], categories=[2, 3],
 7               ordered=False, dtype='category')
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us