
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Set Categories of CategoricalIndex to Unordered in Python Pandas
To set the categories of the CategoricalIndex to be unordered, use the as_unordered() method in Pandas.
At first, import the required libraries −
import pandas as pd
Set the categories for the categorical using the "categories" parameter. Treat the categorical as ordered using the "ordered" parameter with value True −
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
Set the categories to be unordered −
print("\nCategoricalIndex unordered...\n", catIndex.as_unordered())
Example
Following is the code −
import pandas as pd # Set the categories for the categorical using the "categories" parameter # Treat the categorical as ordered using the "ordered" parameter with value True catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"]) # Display the CategoricalIndex print("CategoricalIndex...\n",catIndex) # Get the categories print("\nDisplaying Categories from CategoricalIndex...\n",catIndex.categories) # Set the categories to be unordered print("\nCategoricalIndex unordered...\n", catIndex.as_unordered())
Output
This will produce the following output −
CategoricalIndex... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category') Displaying Categories from CategoricalIndex... Index(['p', 'q', 'r', 's'], dtype='object') CategoricalIndex unordered... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=False, dtype='category')
Advertisements