Python - 檢查 Pandas 索引是否包含類別資料


如需檢查 Pandas 索引是否包含類別資料,請在 Pandas 中使用 index.is_categorical() 方法。首先,匯入必需的庫 -

import pandas as pd

使用 astype() 方法建立帶有型別設定為 category 的 Pandas 索引 −

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

顯示 Pandas 索引 −

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

更新於: 13-Oct-2021

1 千+ 瀏覽量

啟動您的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.