Python Pandas - 确定两个 CategoricalIndex 对象是否包含相同元素
pythonserver side programmingprogramming更新于 2026/1/15 11:24:17
要确定两个 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("\n检查两个 CategoricalIndex 对象是否相等...\n",catIndex1.equals(catIndex2))
示例
以下是代码 −
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"])
# 显示 CategoricalIndex 对象
print("CategoricalIndex1...\n",catIndex1)
print("\nCategoricalIndex2...\n",catIndex2)
# 检查两个 CategoricalIndex 对象是否相等
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
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

