หากต้องการตรวจสอบว่าดัชนี Pandas เก็บข้อมูลที่เป็นหมวดหมู่หรือไม่ ให้ใช้ index.is_categorical() วิธีการในแพนด้า ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
import pandas as pd
การสร้างดัชนี Pandas โดยตั้งค่าประเภทเป็น หมวดหมู่ โดยใช้ astype() วิธีการ −
index = pd.Index(["Electronics","Accessories","Furniture"]).astype("category")
แสดงดัชนีหมีแพนด้า −
print("Pandas Index...\n",index) ตรวจสอบว่าดัชนีเก็บข้อมูลหมวดหมู่หรือไม่ -
print("\nDoes Index holds categorical data?\n",index.is_categorical()) ตัวอย่าง
ต่อไปนี้เป็นรหัส -
import pandas as pd
# Creating Pandas index
index = pd.Index(["Electronics","Accessories","Furniture"]).astype("category")
# Display the Pandas index
print("Pandas Index...\n",index)
# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)
# Return the dtype of the data
print("\nThe dtype...\n",index.dtype)
# check whether index holds categorical data
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