Pandas में श्रेणियों को पुनर्क्रमित करने के लिए CategoricalIndex reorder_categories() मेथड का उपयोग करें।
आवश्यक लाइब्रेरी इम्पोर्ट करें
import pandas as pd
CategoricalIndex बनाएं
"categories" पैरामीटर का उपयोग करके श्रेणियां सेट करें। "ordered" पैरामीटर का उपयोग करके श्रेणी को क्रमबद्ध मानें।
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
CategoricalIndex प्रदर्शित करें
print("CategoricalIndex...\n", catIndex)
श्रेणियां प्राप्त करें
print("\nDisplaying Categories from CategoricalIndex...\n", catIndex.categories)
श्रेणियों को पुनर्क्रमित करें
reorder_categories() का उपयोग करके श्रेणियों को नए क्रम में सेट करें।
print("\nCategoricalIndex after reordering categories...\n", catIndex.reorder_categories(["r", "s", "q", "p"]))
पूरा उदाहरण
import pandas as pd
# श्रेणियां सेट करें और क्रमबद्ध मानें
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
# CategoricalIndex प्रदर्शित करें
print("CategoricalIndex...\n", catIndex)
# श्रेणियां प्राप्त करें
print("\nDisplaying Categories from CategoricalIndex...\n", catIndex.categories)
# श्रेणियों को पुनर्क्रमित करें
print("\nCategoricalIndex after reordering categories...\n", catIndex.reorder_categories(["r", "s", "q", "p"]))
आउटपुट
CategoricalIndex... 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')
CategoricalIndex after reordering categories... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['r', 's', 'q', 'p'], ordered=True, dtype='category')
व्याख्या: reorder_categories() श्रेणियों के क्रम को बदलता है लेकिन मान अपरिवर्तित रहते हैं। नया क्रम: r, s, q, p।