Python Pandas - 判断两个 CategoricalIndex 对象是否包含相同的元素


要确定两个 CategoricalIndex 对象是否包含相同的元素,请使用 equals() 方法。首先,导入所需的库 −

import pandas as pd

使用 "categories" 参数为分类设置类别。使用 "ordered" 参数将类别视为有序的。创建两个 CategoricalIndex 对象 −

catIndex1 = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
catIndex2 = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])

检查两个 CategoricalIndex 对象是否相等 −

print("\nCheck both the CategoricalIndex objects for equality...\n",catIndex1.equals(catIndex2))

示例

以下是代码 −

import pandas as pd

# Set the categories for the categorical using the "categories" parameter
# Treat the categorical as ordered using the "ordered" parameter
# Create two CategoricalIndex objects
catIndex1 = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
catIndex2 = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])

# Display the CategoricalIndex objects
print("CategoricalIndex1...\n",catIndex1)
print("\nCategoricalIndex2...\n",catIndex2)

# Check both the CategoricalIndex objects for equality
print("\nCheck both the CategoricalIndex objects for equality...\n",catIndex1.equals(catIndex2))

输出

这将产生以下输出 −

CategoricalIndex1...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')

CategoricalIndex2...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')

Check both the CategoricalIndex objects for equality...
True

更新于: 18-Oct-2021

84 次浏览

开启你的事业

完成课程以获得认证

开始
广告