用法:
class pandas.Categorical(values, categories=None, ordered=None, dtype=None, fastpath=False, copy=True)
以經典 R /S-plus 方式表示分類變量。
Categoricals
隻能采用有限且通常是固定數量的可能值 (categories
)。與統計分類變量相比,Categorical
可能有順序,但不能進行數值運算(加法、除法等)。Categorical
的所有值都在categories
或np.nan
中。在categories
之外分配值將引發ValueError
。順序由categories
的順序定義,而不是值的詞法順序。- values:list-like
分類的值。如果給定類別,則不在類別中的值將替換為 NaN。
- categories:Index-like(唯一),可選
此類別的唯一類別。如果未給出,則假定類別是
values
的唯一值(如果可能,按它們出現的順序排序)。- ordered:布爾值,默認為 False
此分類是否被視為有序分類。如果為 True,則將對生成的分類進行排序。排序後的分類尊重其
categories
屬性的順序(如果提供,該屬性又是categories
參數)。- dtype:分類類型
用於此分類的
CategoricalDtype
的實例。
- ValueError
如果類別不驗證。
- TypeError
如果給出了明確的
ordered=True
但沒有給出categories
並且values
是不可排序的。
參數:
拋出:
注意:
有關更多信息,請參閱用戶指南。
例子:
>>> pd.Categorical([1, 2, 3, 1, 2, 3]) [1, 2, 3, 1, 2, 3] Categories (3, int64):[1, 2, 3]
>>> pd.Categorical(['a', 'b', 'c', 'a', 'b', 'c']) ['a', 'b', 'c', 'a', 'b', 'c'] Categories (3, object):['a', 'b', 'c']
缺失值不作為一個類別包括在內。
>>> c = pd.Categorical([1, 2, 3, 1, 2, 3, np.nan]) >>> c [1, 2, 3, 1, 2, 3, NaN] Categories (3, int64):[1, 2, 3]
但是,它們的存在在
codes
屬性中由代碼-1
指示。>>> c.codes array([ 0, 1, 2, 0, 1, 2, -1], dtype=int8)
Ordered
Categoricals
可以根據類別的自定義順序進行排序,可以有最小值和最大值。>>> c = pd.Categorical(['a', 'b', 'c', 'a', 'b', 'c'], ordered=True, ... categories=['c', 'b', 'a']) >>> c ['a', 'b', 'c', 'a', 'b', 'c'] Categories (3, object):['c' < 'b' < 'a'] >>> c.min() 'c'
相關用法
- Python pandas.CategoricalIndex.add_categories用法及代碼示例
- Python pandas.CategoricalIndex.remove_unused_categories用法及代碼示例
- Python pandas.CategoricalIndex.remove_categories用法及代碼示例
- Python pandas.CategoricalIndex.map用法及代碼示例
- Python pandas.CategoricalIndex.rename_categories用法及代碼示例
- Python pandas.Categorical.from_codes用法及代碼示例
- Python pandas.CategoricalDtype用法及代碼示例
- Python pandas.CategoricalIndex用法及代碼示例
- Python pandas.arrays.IntervalArray.is_empty用法及代碼示例
- Python pandas.DataFrame.ewm用法及代碼示例
- Python pandas.api.types.is_timedelta64_ns_dtype用法及代碼示例
- Python pandas.DataFrame.dot用法及代碼示例
- Python pandas.DataFrame.apply用法及代碼示例
- Python pandas.DataFrame.combine_first用法及代碼示例
- Python pandas.read_pickle用法及代碼示例
- Python pandas.Index.value_counts用法及代碼示例
- Python pandas.DatetimeTZDtype用法及代碼示例
- Python pandas.DataFrame.cumsum用法及代碼示例
- Python pandas.Interval.is_empty用法及代碼示例
- Python pandas.api.indexers.FixedForwardWindowIndexer用法及代碼示例
注:本文由純淨天空篩選整理自pandas.pydata.org大神的英文原創作品 pandas.Categorical。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。