(資料科學學習手札68)pandas中的categorical型別及應用
一、簡介
categorical是pandas中對應分類變數的一種資料型別,與R中的因子型變數比較相似,例如性別、血型等等用於表徵類別的變數都可以用其來表示,本文就將針對categorical的相關內容及應用進行介紹。
二、建立與應用
2.1 基本特性和適用場景
在介紹具體方法之前,我們需要對pandas資料型別中的categorical型別有一個瞭解,categorical類似R中的因子型變數,可以進行排序操作,但不可以進行數值運算操作,其順序在其被定義的時候一同確定,而不是按照數字字母詞法排序的順序,其適用場景有如下幾個:
1、具有少數幾種可能取值並存在大量重複的字串欄位,利用categorical型別對其轉換後可有效節省記憶體
2、欄位的排序規則特殊,不遵循詞法順序時,可以利用categorical型別對其轉換後得到使用者所需的排序規則、
2.2 建立方式
pandas中建立categorical型資料主要有如下幾種方式:
1、對於Series資料結構,傳入引數dtype='category'即可:
#直接建立categorical型Series series_cat = pd.Series(['B','D','C','A'], dtype='category') #顯示Series資訊 series_cat
可以看到,series_cat的型別為category,但是沒有宣告順序,這時若對Series排序,實際上還是按照詞法的順序:
series_cat.sort_values()
2、對於DataFrame,在定義資料之後轉換型別:
#建立資料框 df_cat = pd.DataFrame({ 'V1':['A','C','B','D'] }) #轉換指定列的資料型別為category df_cat['V1'] = df_cat['V1'].astype('category') df_cat['V1']
3、利用pd.Categorical()生成類別型資料後轉換為Series,或替換DataFrame中的內容:
categorical_ = pd.Categorical(['A','B','D','C'], categories=['A','B','C','D']) series_cat = pd.Series(categorical_) series_cat
categorical_ = pd.Categorical(['A','B','D','C'], categories=['A','B','C','D']) df_cat = pd.DataFrame({ 'V1':categorical_ }) df_cat['V1']
而pd.Categorical()獨立建立categorical資料時有兩個新的特性,一是其通過引數categories定義類別時,若原資料中出現了categories引數中沒有的資料,則會自動轉換為pd.nan:
categorical_ = pd.Categorical(['A','B','D','C'], categories=['B','C','D']) df_cat = pd.DataFrame({ 'V1':categorical_ }) df_cat['V1']
另外pd.Categorical()還有一個bool型引數ordered,設定為True時則會按照categories中的順序定義從小到大的範圍:
categorical_ = pd.Categorical(['A','B','D','C'], categories=['A','B','C','D'], ordered=True) df_cat = pd.DataFrame({ 'V1':categorical_ }) df_cat['V1']
4、利用pandas.api.types中的CategoricalDtype()對已有資料進行轉換
通過CategoricalDtype(),我們可以結合astype()完成從其他型別資料向categorical資料的轉換過程,利用CategoricalDtype()的引數categories、ordered,彌補.astype('category')的短板(實際上.astype('category')等價於.astype(CategoricalDtype(categories=None, ordered=False))):
from pandas.api.types import CategoricalDtype #建立資料框 df_cat = pd.DataFrame({ 'V1':['A','C','B','D'] }) cat = CategoricalDtype(categories=['A','C','B'], ordered=True) df_cat['V1'] = df_cat['V1'].astype(cat) df_cat['V1']
2.3 應用
categorical型資料主要應用於自定義排序,如下例,我們建立了一個包含字元型變數class和數值型變數value的資料框:
import numpy as np df = pd.DataFrame({ 'class':np.random.choice(['A','B','C','D'],10), 'value':np.random.uniform(0,10,10) }) df.head()
如果按照class列排序得到的結果是按照字母自然順序:
df.sort_values('class')
而通過將class列修改為自己定義的排序方式則得到的結果如下:
from pandas.api.types import CategoricalDtype cat = CategoricalDtype(categories=['B','D','A','C'], ordered=True) df['class'] = df['class'].astype(cat) df.sort_values('class')
若想要臨時修改排序規則,可以使用.cat.reorder_categories()方法:
df['class'].cat.reorder_categories(['D','B','C','A'], ordered=True, inplace=True)#iinplace引數設定為True使得變動覆蓋原資料 df.sort_values('class')
關於pandas中的categorical型資料還有很多的小技巧,因為不常用這裡就不再贅述,感興趣可以檢視pandas的官方文件,以上就是本文的全部內容,如有筆誤望指出!
&n