Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - ตรวจสอบว่า Pandas Index เป็นชนิดข้อมูล object หรือไม่

การตรวจสอบ dtype ของ Index ว่าเป็น object

ใช้เมธอด index.is_object() เพื่อตรวจสอบว่า Index มีชนิดข้อมูล object หรือไม่ (object หมายถึงข้อมูลหลากหลายชนิดหรือสตริง)

ขั้นตอน

  1. นำเข้า pandas
  2. สร้าง Index ที่มีข้อมูลผสม (สตริงและตัวเลข)
  3. แสดง Index
  4. ใช้ 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 ในกรณีนี้