การตรวจสอบว่า Index เป็น categorical data
ใช้เมธอด index.is_categorical() ตรวจสอบว่า Index เป็น CategoricalIndex หรือไม่
ขั้นตอน
- นำเข้า pandas
- สร้าง Index และแปลงเป็น categorical ด้วย
astype('category') - แสดง Index
- ใช้
is_categorical()ตรวจสอบ
ตัวอย่างโค้ด
import pandas as pd
# สร้าง Index และแปลงเป็น category
index = pd.Index(["Electronics", "Accessories", "Furniture"]).astype("category")
# แสดง Index
print("Pandas Index...\n", index)
# แสดงจำนวนองค์ประกอบและ dtype
print("\nNumber of elements in the index...\n", index.size)
print("\nThe dtype...\n", index.dtype)
# ตรวจสอบว่าเป็น categorical
print("\nDoes Index holds categorical data?\n", index.is_categorical())
ผลลัพธ์
Pandas Index... CategoricalIndex(['Electronics', 'Accessories', 'Furniture'], categories=['Accessories', 'Electronics', 'Furniture'], ordered=False, dtype='category') Number of elements in the index... 3 The dtype... category Does Index holds categorical data? True
ประโยชน์
เหมาะสำหรับข้อมูลหมวดหมู่ที่มีค่าซ้ำกันมาก ช่วยประหยัดหน่วยความจำและเพิ่มประสิทธิภาพ