Python Pandas - 分類資料



在 Pandas 中,分類資料指的是表示分類變數的資料型別,類似於 R 中的因子概念。它是一種專門用於處理分類變數的資料型別,通常用於統計學。

分類變數可以表示諸如“男性”或“女性”之類的值,或者表示諸如“差”、“中等”和“優秀”之類的等級。與數值資料不同,您無法對分類資料執行加法或除法等數學運算。

在 Pandas 中,分類資料儲存得更有效率,因為它使用類別值的陣列和引用這些類別的整數程式碼的陣列的組合。這節省了記憶體,並在處理包含重複值的大型資料集時提高了效能。

分類資料型別在以下情況下很有用:

  • 僅包含幾個不同值的字串變數。將此類字串變數轉換為分類變數將節省一些記憶體。

  • 變數的詞法順序與邏輯順序不同(“一”、“二”、“三”)。透過轉換為分類變數並在類別上指定順序,排序和最小/最大值將使用邏輯順序而不是詞法順序。

  • 作為其他 Python 庫的訊號,該列應被視為分類變數(例如,使用合適的統計方法或繪圖型別)。

在本教程中,我們將學習 Pandas 中處理分類資料的基礎知識,包括 Series 和 DataFrame 的建立、行為控制以及從分類值中恢復原始資料。

建立包含分類資料的 Series

可以使用 Pandas Series()DataFrame() 建構函式的 dtype="category" 引數直接使用分類資料建立 Pandas Series 或 DataFrame 物件。

示例

以下是使用分類資料建立 Pandas Series 物件的基本示例。

import pandas as pd

# Create Series object with categorical data
s = pd.Series(["a", "b", "c", "a"], dtype="category")

# Display the categorical Series 
print('Series with Categorical Data:\n', s)

以下是上述程式碼的輸出:

Series with Categorical Data:
0    a
1    b
2    c
3    a
dtype: category

Categories (3, object): ['a', 'b', 'c']

示例:將現有 DataFrame 列轉換為分類資料

此示例演示如何使用 astype() 方法將現有的 Pandas DataFrame 列轉換為分類資料型別。

import pandas as pd
import numpy as np

# Create a DataFrame 
df = pd.DataFrame({"Col_a": list("aeeioou"), "Col_b": range(7)})

# Display the Input DataFrame
print('Input DataFrame:\n',df)
print('Verify the Data type of each column:\n', df.dtypes)

# Convert the Data type of col_a to categorical
df['Col_a'] = df["Col_a"].astype("category")

# Display the Input DataFrame
print('Converted DataFrame:\n',df)
print('Verify the Data type of each column:\n', df.dtypes)

以下是上述程式碼的輸出:

Input DataFrame:
   Col_a  Col_b
0     a      0
1     e      1
2     e      2
3     i      3
4     o      4
5     o      5
6     u      6

Verify the Data type of each column:
Col_a    object
Col_b     int64
dtype: object

Converted DataFrame:
   Col_a  Col_b
0     a      0
1     e      1
2     e      2
3     i      3
4     o      4
5     o      5
6     u      6

Verify the Data type of each column:
Col_a    category
Col_b       int64
dtype: object

控制分類資料行為

預設情況下,Pandas 從資料中推斷類別並將它們視為無序的。要控制行為,您可以使用 pandas.api.types 模組中的 CategoricalDtype 類。

示例

此示例演示如何將 CategoricalDtype 應用於整個 DataFrame。

import pandas as pd
from pandas.api.types import CategoricalDtype

# Create a DataFrame 
df = pd.DataFrame({"A": list("abca"), "B": list("bccd")})

# Display the Input DataFrame
print('Input DataFrame:\n',df)
print('Verify the Data type of each column:\n', df.dtypes)

# Applying CategoricalDtype to a DataFrame
cat_type = CategoricalDtype(categories=list("abcd"), ordered=True)
df_cat = df.astype(cat_type)

# Display the Input DataFrame
print('Converted DataFrame:\n', df_cat)
print('Verify the Data type of each column:\n', df_cat.dtypes)

以下是上述程式碼的輸出:

Input DataFrame:
    A  B
0  a  b
1  b  c
2  c  c
3  a  d
Verify the Data type of each column:
 A    object
B    object
dtype: object
Converted DataFrame:
    A  B
0  a  b
1  b  c
2  c  c
3  a  d
Verify the Data type of each column:
 A    category
B    category

將分類資料轉換回原始資料

將 Series 轉換為分類資料後,可以使用 Series.astype()np.asarray() 將其轉換回原始形式。

示例

此示例使用 astype() 方法將 Series 物件的分類資料轉換回物件資料型別。

import pandas as pd

# Create Series object with categorical data
s = pd.Series(["a", "b", "c", "a"], dtype="category")

# Display the categorical Series 
print('Series with Categorical Data:\n', s)

# Display the converted Series
print('Converted Seriesbac to original:\n ', s.astype(str))

以下是上述程式碼的輸出:

Series with Categorical Data:
 0    a
1    b
2    c
3    a
dtype: category
Categories (3, object): ['a', 'b', 'c']
Converted Seriesbac to original:
  0    a
1    b
2    c
3    a
dtype: object

使用 describe 命令

對分類資料使用 .describe() 命令,我們將獲得與 type 為字串的 SeriesDataFrame 類似的輸出。

import pandas as pd
import numpy as np

cat = pd.Categorical(["a", "c", "c", np.nan], categories=["b", "a", "c"])
df = pd.DataFrame({"cat":cat, "s":["a", "c", "c", np.nan]})

print(df.describe())
print(df["cat"].describe())

輸出如下:

       cat s
count    3 3
unique   2 2
top      c c
freq     2 2
count     3
unique    2
top       c
freq      2
Name: cat, dtype: object
廣告