Python Pandas – 设置无序CategoricalIndex的类别
要将CategoricalIndex的类别设置为无序,请使用Pandas中的as_unordered()方法。
首先,导入所需的库 –
import pandas as pd
使用“类别”参数设置类别。使用值为True的“ordered”参数将分类视为已排序 –
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
设置为无序类别 –
print("\nCategoricalIndex unordered...\n", catIndex.as_unordered())
例子
如下是代码 –
import pandas as pd
# 使用“类别”参数设置分类类别
# 使用值为True的“ordered”参数将分类视为已排序
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
# 显示CategoricalIndex
print("CategoricalIndex...\n", catIndex)
# 获取类别
print("\nDisplaying Categories from CategoricalIndex...\n", catIndex.categories)
# 设置为无序类别
print("\nCategoricalIndex unordered...\n", catIndex.as_unordered())
输出
这将产生以下输出 –
CategoricalIndex...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')
显示CategoricalIndex的类别...
Index(['p', 'q', 'r', 's'], dtype='object')
CategoricalIndex无序...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=False, dtype='category')