Python Pandas - 將 CategoricalIndex 的類別設定為有序
若要將 CategoricalIndex 的類別設定為有序,請在 Pandas 中使用 as_ordered() 方法。
首先,匯入所需的庫 -
import pandas as pd
使用 "categories" 引數為類別設定類別 -
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], categories=["p", "q", "r", "s"])
獲取類別 -
print("\nDisplaying Categories from CategoricalIndex...\n",catIndex.categories)
將類別設定為有序 -
print("\nCategoricalIndex ordered...\n", catIndex.as_ordered())例
以下是程式碼 -
import pandas as pd
# Set the categories for the categorical using the "categories" parameter
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], categories=["p", "q", "r", "s"])
# Display the CategoricalIndex
print("CategoricalIndex...\n",catIndex)
# Get the categories
print("\nDisplaying Categories from CategoricalIndex...\n",catIndex.categories)
# Set the categories to be ordered
print("\nCategoricalIndex ordered...\n", catIndex.as_ordered())輸出
這將生成以下輸出 -
CategoricalIndex... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=False, dtype='category') Displaying Categories from CategoricalIndex... Index(['p', 'q', 'r', 's'], dtype='object') CategoricalIndex ordered... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP