Pandas में CategoricalIndex की श्रेणियों को क्रमबद्ध सेट करने के लिए as_ordered() मेथड का उपयोग करें।
आवश्यक लाइब्रेरी इम्पोर्ट करें
import pandas as pd
CategoricalIndex बनाएं
"categories" पैरामीटर का उपयोग करके श्रेणियां सेट करें।
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"], categories=["p", "q", "r", "s"])
श्रेणियां प्राप्त करें
print("\nDisplaying Categories from CategoricalIndex...\n", catIndex.categories)
श्रेणियों को क्रमबद्ध सेट करें
print("\nCategoricalIndex ordered...\n", catIndex.as_ordered())
पूरा उदाहरण
import pandas as pd
# श्रेणियां सेट करें
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"], categories=["p", "q", "r", "s"])
# CategoricalIndex प्रदर्शित करें
print("CategoricalIndex...\n", catIndex)
# श्रेणियां प्राप्त करें
print("\nDisplaying Categories from CategoricalIndex...\n", catIndex.categories)
# श्रेणियों को क्रमबद्ध सेट करें
print("\nCategoricalIndex ordered...\n", catIndex.as_ordered())
आउटपुट
CategoricalIndex... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=False, dtype='category')
Displaying Categories from CategoricalIndex... Index(['p', 'q', 'r', 's'], dtype='object')
CategoricalIndex ordered... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')
व्याख्या: as_ordered() मेथड श्रेणियों को क्रमबद्ध (ordered=True) सेट करके नया CategoricalIndex लौटाता है।