Python Pandas CategoricalIndex - Get the category codes of this categorical

PythonServer Side ProgrammingProgramming

To get the category codes of this categorical, use the codes property of the CategoricalIndex in Pandas. At first, import the required libraries −

import pandas as pd

CategoricalIndex can only take on a limited, and usually fixed, number of possible values (categories). Set the categories for the categorical using the "categories" parameter. Treat the categorical as ordered using the "ordered" parameter. Codes are an array of integers which are the positions of the actual values in the categories array −

catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])

Display the Categorical Index −

print("Categorical Index...\n",catIndex)

Get the category codes −

print("\nCategory codes from CategoricalIndex...\n",catIndex.codes)

Example

Following is the code −

import pandas as pd

# CategoricalIndex can only take on a limited, and usually fixed, number of possible values
# Set the categories for the categorical using the "categories" parameter
# Treat the categorical as ordered using the "ordered" parameter
# Codes are an array of integers which are the positions of the actual values in the categories array.
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])

# Display the Categorical Index
print("Categorical Index...\n",catIndex)

# Get the categories
print("\nDisplayingCategories from CategoricalIndex...\n",catIndex.categories)

# Get the category codes
print("\nCategory codes from CategoricalIndex...\n",catIndex.codes)

Output

This will produce the following output −

Categorical Index...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')

DisplayingCategories from CategoricalIndex...
Index(['p', 'q', 'r', 's'], dtype='object')

Category codes from CategoricalIndex...
[0 1 2 3 0 1 2 3]
raja
Published on 18-Oct-2021 06:38:25
Advertisements