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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP