Python Pandas CategoricalIndex - 添加新的类型
如要添加新类型,请在 Pandas 中使用 CategoricalIndex add_categories() 方法。首先,导入必需的库 −
import pandas as pd
使用 "categories" 参数为类型设置类型。使用 "ordered" 参数将类型视为有序类型 −
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
显示 CategoricalIndex −
print("CategoricalIndex...\n",catIndex)
使用 add_categories() 添加新类型。将新类型作为一个参数设置。新类型将包含在类型中的最后/最高位置 −
print("\nCategoricalIndex after adding new categories...\n",catIndex.add_categories(["a", "b", "c", "d"]))示例
以下为代码 −
import pandas as pd
# CategoricalIndex can only take on a limited, and usually fixed, number of possible values (categories
# Set the categories for the categorical using the "categories" parameter
# Treat the categorical as ordered using the "ordered" parameter
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
# Display the CategoricalIndex
print("CategoricalIndex...\n",catIndex)
# Get the categories
print("\nDisplayingCategories from CategoricalIndex...\n",catIndex.categories)
# Add new categories using add_categories()
# Set the new categories as a parameter
# The new categories will be included at the last/highest place in the categories
print("\nCategoricalIndex after adding new categories...\n",catIndex.add_categories(["a", "b", "c", "d"]))输出
这将生成以下输出 −
CategoricalIndex... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category') DisplayingCategories from CategoricalIndex... Index(['p', 'q', 'r', 's'], dtype='object') CategoricalIndex after adding new categories... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's', 'a', 'b', 'c', 'd'], ordered=True, dtype='category')
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP