Python Pandas - 确定两个 CategoricalIndex 对象是否包含相同的元素
要确定两个CategoricalIndex对象是否包含相同的元素,请使用该equals()方法。首先,导入所需的库-
import pandas as pd
使用“categories”参数设置分类的类别。使用“有序”参数将分类视为有序。创建两个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
#创建两个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("\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