หากต้องการดึงหมวดหมู่ (categories) ของข้อมูลประเภท Categorical ให้ใช้ property categories ของ CategoricalIndex ใน Pandas ก่อนอื่น ให้นำเข้าไลบรารีที่จำเป็น:
import pandas as pd
CategoricalIndex สามารถรับค่าได้เพียงจำนวนจำกัดและมักจะเป็นค่าคงที่ (categories) ให้ตั้งค่าหมวดหมู่โดยใช้พารามิเตอร์ categories และกำหนดลำดับข้อมูลด้วยพารามิเตอร์ ordered:
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
แสดง Categorical Index:
print("Categorical Index...\n", catIndex)
ดึงหมวดหมู่:
print("\nDisplaying Categories from CategoricalIndex...\n", catIndex.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"])
# แสดง Categorical Index
print("Categorical Index...\n", catIndex)
# ดึงหมวดหมู่
print("\nDisplaying Categories from CategoricalIndex...\n", catIndex.categories)
ผลลัพธ์
โค้ดจะให้ผลลัพธ์ดังนี้:
Categorical Index... 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')