Pandas में CategoricalIndex से निर्दिष्ट श्रेणियां हटाने के लिए remove_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"])
निर्दिष्ट श्रेणियां हटाएं
remove_categories() का उपयोग करके श्रेणियां हटाएं। हटाई जाने वाली श्रेणियों को पैरामीटर के रूप में सेट करें। हटाई गई श्रेणियों में मौजूद मान NaN पर सेट हो जाएंगे।
print("\nCategoricalIndex after removing specified categories...\n", catIndex.remove_categories(["p", "q"]))
पूरा उदाहरण
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 removing specified categories...\n", catIndex.remove_categories(["p", "q"]))
आउटपुट
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 after removing specified categories... CategoricalIndex([nan, nan, 'r', 's', nan, nan, 'r', 's'], categories=['r', 's'], ordered=True, dtype='category')
व्याख्या: श्रेणियां "p" और "q" हटा दी गई हैं, इसलिए उन मानों वाले तत्व NaN बन जाते हैं। शेष श्रेणियां "r" और "s" हैं।