當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python pandas.CategoricalIndex用法及代碼示例

用法:

class pandas.CategoricalIndex(data=None, categories=None, ordered=None, dtype=None, copy=False, name=None)

基於基礎 Categorical 的索引。

CategoricalIndex 與 Categorical 一樣,隻能采用有限且通常是固定數量的可能值 (categories)。此外,與分類一樣,它可能有順序,但不可能進行數值運算(加法、除法等)。

參數

dataarray-like(一維)

分類的值。如果給出categories,則不在categories 中的值將被替換為NaN。

categoriesindex-like,可選

類別的類別。項目必須是唯一的。如果這裏沒有給出類別(也沒有在 dtype 中),它們將從 data 中推斷出來。

ordered布爾型,可選

此分類是否被視為有序分類。如果未在此處或 dtype 中給出,則生成的分類將是無序的。

dtypeCategoricalDtype 或“category”,可選

如果 CategoricalDtype ,不能與 categoriesordered 一起使用。

copy布爾值,默認為 False

製作輸入 ndarray 的副本。

name對象,可選

要存儲在索引中的名稱。

拋出

ValueError

如果類別不驗證。

TypeError

如果給出了明確的 ordered=True 但沒有給出 categories 並且 values 是不可排序的。

注意

有關更多信息,請參閱用戶指南。

例子

>>> pd.CategoricalIndex(["a", "b", "c", "a", "b", "c"])
CategoricalIndex(['a', 'b', 'c', 'a', 'b', 'c'],
                 categories=['a', 'b', 'c'], ordered=False, dtype='category')

CategoricalIndex 也可以從 Categorical 實例化:

>>> c = pd.Categorical(["a", "b", "c", "a", "b", "c"])
>>> pd.CategoricalIndex(c)
CategoricalIndex(['a', 'b', 'c', 'a', 'b', 'c'],
                 categories=['a', 'b', 'c'], ordered=False, dtype='category')

已排序的 CategoricalIndex 可以具有最小值和最大值。

>>> ci = pd.CategoricalIndex(
...     ["a", "b", "c", "a", "b", "c"], ordered=True, categories=["c", "b", "a"]
... )
>>> ci
CategoricalIndex(['a', 'b', 'c', 'a', 'b', 'c'],
                 categories=['c', 'b', 'a'], ordered=True, dtype='category')
>>> ci.min()
'c'

相關用法


注:本文由純淨天空篩選整理自pandas.pydata.org大神的英文原創作品 pandas.CategoricalIndex。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。