Python Pandas – 如何确定两个 CategoricalIndex 对象是否包含相同的元素
使用 equals() 方法来确定两个 CategoricalIndex 对象是否包含相同的元素。首先,导入所需的库−
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))
更多Pandas相关文章,请阅读:Pandas 教程
示例
下面是代码−
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("CategoricalIndex1...\n",catIndex1)
print("\nCategoricalIndex2...\n",catIndex2)
# 检查两个 CategoricalIndex 对象是否相等
print("\n检查两个 CategoricalIndex 对象是否相等...\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')
检查两个 CategoricalIndex 对象是否相等...
True
极客教程