เมธอด remove_categories() ใช้ลบหมวดหมู่ที่ระบุออกจาก CategoricalIndex ค่าที่อยู่ในหมวดหมู่ที่ถูกลบจะกลายเป็น NaN หมวดหมู่ที่เหลือจะคงลำดับเดิม
ตัวอย่างโค้ด
import pandas as pd
catIndex = pd.CategoricalIndex(
["p", "q", "r", "s", "p", "q", "r", "s"],
ordered=True,
categories=["p", "q", "r", "s"]
)
print("CategoricalIndex เดิม:\n", catIndex)
print("\nหมวดหมู่เดิม:\n", catIndex.categories)
# ลบหมวดหมู่ p และ q
result = catIndex.remove_categories(["p", "q"])
print("\nCategoricalIndex หลังลบ p, q:\n", result)
ผลลัพธ์
CategoricalIndex เดิม: CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category') หมวดหมู่เดิม: Index(['p', 'q', 'r', 's'], dtype='object') CategoricalIndex หลังลบ p, q: CategoricalIndex([nan, nan, 'r', 's', nan, nan, 'r', 's'], categories=['r', 's'], ordered=True, dtype='category')
ค่า p และ q กลายเป็น NaN หมวดหมู่เหลือแค่ r และ s