pd.Categoricalの使い方


最近データ処理中にpdに遭遇した.Categorical()ということで、まずは公式サイトへのリンクを調べてみましたhttp://pandas.pydata.org/pandas-docs/stable/generated/pandas.Categorical.html
私たちは直接例を通して勉強します.
In [16]: st = ['a','a','b','c','c']

In [17]: ss = pd.Categorical(st)

In [18]: ss
Out[18]:
[a, a, b, c, c]
Categories (3, object): [a, b, c]

In [22]: ss.dtype
Out[22]: CategoricalDtype(categories=['a', 'b', 'c'], ordered=False)


        categorical                    ,     ,       CategoricalDtype      ,                 ,
                     codes    categories    :


In [23]: ss.codes
Out[23]: array([0, 0, 1, 2, 2], dtype=int8)
In [21]: ss.categories
Out[21]: Index(['a', 'b', 'c'], dtype='object')

実際の応用では、私たちはよく彼のcodes属性と組み合わせて使用します.すなわちpd.Categorical( list ).codesは、元のデータの対応するシーケンス番号リストを直接得ることができ、このような処理によってカテゴリ情報を数値情報に変換することができ、モデルに適用してより詳細な機能参照公式サイトを参照することができる.
実はここを見てCategoricalの機能と以前機械学習データ処理部分で述べたLabelEncoder(https://blog.csdn.net/weixin_38656890/article/details/80849334)の機能は同じですが、Categoricalは自己符号化であり、LabelEncoderは1つのサンプルで標準化され、他のサンプルで符号化されるので、相対的に柔軟です.
更新:
ちなみにfactorize pd.Categorical 的用法_第1张图片