การตรวจสอบ dtype ของ Index ว่าเป็น object
ใช้เมธอด index.is_object() เพื่อตรวจสอบว่า Index มีชนิดข้อมูล object หรือไม่ (object หมายถึงข้อมูลหลากหลายชนิดหรือสตริง)
ขั้นตอน
- นำเข้า pandas
- สร้าง Index ที่มีข้อมูลผสม (สตริงและตัวเลข)
- แสดง Index
- ใช้
is_object()ตรวจสอบ
ตัวอย่างโค้ด
import pandas as pd
# สร้าง Index ข้อมูลผสม
index = pd.Index(["Electronics", 6, 10.5, "Accessories", 25.6, 30])
# แสดง Index
print("Pandas Index...\n", index)
# แสดงจำนวนองค์ประกอบและ dtype
print("\nNumber of elements in the index...\n", index.size)
print("\nThe dtype object...\n", index.dtype)
# ตรวจสอบว่าเป็น object dtype
print("\nIs the Index of object dtype?\n", index.is_object())
ผลลัพธ์
Pandas Index... Index(['Electronics', 6, 10.5, 'Accessories', 25.6, 30], dtype='object') Number of elements in the index... 6 The dtype object... object Is the Index of object dtype? True
คำอธิบาย
เมื่อ Index มีข้อมูลหลายชนิดปนกัน (สตริง, int, float) Pandas จะกำหนด dtype เป็น 'object' เมธอด is_object() จะคืนค่า True ในกรณีนี้