Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python - Kiểm tra Pandas Index có chứa dữ liệu categorical không


Để kiểm tra xem Pandas Index có chứa dữ liệu categorical hay không, hãy sử dụng phương thức index.is_categorical() trong Pandas. Trước tiên, nhập các thư viện cần thiết:

import pandas as pd

Tạo Pandas Index với kiểu được đặt là category sử dụng phương thức astype():

index = pd.Index(["Electronics","Accessories","Furniture"]).astype("category")

Hiển thị Pandas Index:

print("Pandas Index...\n", index)

Kiểm tra xem index có chứa dữ liệu categorical:

print("\nIndex có chứa dữ liệu categorical?\n", index.is_categorical())

Ví dụ

Dưới đây là mã hoàn chỉnh:

import pandas as pd
# Tạo Pandas Index
index = pd.Index(["Electronics","Accessories","Furniture"]).astype("category")
# Hiển thị Pandas Index
print("Pandas Index...\n", index)
# Trả về số lượng phần tử trong Index
print("\nSố lượng phần tử trong index...\n", index.size)
# Trả về kiểu dữ liệu
print("\nĐối tượng dtype...\n", index.dtype)
# kiểm tra xem index có chứa dữ liệu categorical
print("\nIndex có chứa dữ liệu categorical?\n", index.is_categorical())

Kết quả

Đoạn mã trên sẽ cho ra kết quả sau:

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