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.