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