เพื่อสร้าง Index จาก Categorical พื้นฐาน ให้ใช้เมธอด pandas.CategoricalIndex()
ก่อนอื่น ให้นำเข้าไลบรารีที่จำเป็น:
import pandas as pd
CategoricalIndex คือ Index ที่พัฒนาจาก Categorical พื้นฐาน สามารถรับค่าได้เพียงจำนวนจำกัดและมักจะเป็นค่าคงที่ ตั้งค่าหมวดหมู่ด้วยพารามิเตอร์ 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("\nDisplayingCategories from CategoricalIndex...\n", catIndex.categories)
ตัวอย่างโค้ดสมบูรณ์
import pandas as pd
# CategoricalIndex คือ Index ที่พัฒนาจาก Categorical พื้นฐาน
# ตั้งค่าหมวดหมู่ด้วยพารามิเตอร์ "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("\nDisplayingCategories from CategoricalIndex...\n", catIndex.categories)
# ดึงค่าต่ำสุด
print("\nMinimum value from CategoricalIndex...\n", catIndex.min())
# ดึงค่าสูงสุด
print("\nMaximum value from CategoricalIndex...\n", catIndex.max())
ผลลัพธ์
โค้ดจะให้ผลลัพธ์ดังนี้:
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') Minimum value from CategoricalIndex... p Maximum value from CategoricalIndex... s