
- Python Pandas 教程
- Python Pandas - 首頁
- Python Pandas - 簡介
- Python Pandas - 環境設定
- Python Pandas - 基礎
- Python Pandas - 資料結構簡介
- Python Pandas - 索引物件
- Python Pandas - 面板
- Python Pandas - 基本功能
- Python Pandas - 索引和資料選擇
- Python Pandas - Series
- Python Pandas - Series
- Python Pandas - 切片 Series 物件
- Python Pandas - Series 物件的屬性
- Python Pandas - Series 物件的算術運算
- Python Pandas - 將 Series 轉換為其他物件
- Python Pandas - DataFrame
- Python Pandas - DataFrame
- Python Pandas - 訪問 DataFrame
- Python Pandas - 切片 DataFrame 物件
- Python Pandas - 修改 DataFrame
- Python Pandas - 從 DataFrame 中刪除行
- Python Pandas - DataFrame 的算術運算
- Python Pandas - I/O 工具
- Python Pandas - I/O 工具
- Python Pandas - 使用 CSV 格式
- Python Pandas - 讀取和寫入 JSON 檔案
- Python Pandas - 從 Excel 檔案讀取資料
- Python Pandas - 將資料寫入 Excel 檔案
- Python Pandas - 使用 HTML 資料
- Python Pandas - 剪貼簿
- Python Pandas - 使用 HDF5 格式
- Python Pandas - 與 SQL 的比較
- Python Pandas - 資料處理
- Python Pandas - 排序
- Python Pandas - 重新索引
- Python Pandas - 迭代
- Python Pandas - 連線
- Python Pandas - 統計函式
- Python Pandas - 描述性統計
- Python Pandas - 處理文字資料
- Python Pandas - 函式應用
- Python Pandas - 選項和自定義
- Python Pandas - 視窗函式
- Python Pandas - 聚合
- Python Pandas - 合併/連線
- Python Pandas - 多級索引
- Python Pandas - 多級索引基礎
- Python Pandas - 使用多級索引進行索引
- Python Pandas - 使用多級索引進行高階重新索引
- Python Pandas - 重新命名多級索引標籤
- Python Pandas - 對多級索引進行排序
- Python Pandas - 二元運算
- Python Pandas - 二元比較運算
- Python Pandas - 布林索引
- Python Pandas - 布林掩碼
- Python Pandas - 資料重塑和透視表
- Python Pandas - 透視表
- Python Pandas - 堆疊和取消堆疊
- Python Pandas - 熔化
- Python Pandas - 計算虛擬變數
- Python Pandas - 分類資料
- Python Pandas - 分類資料
- Python Pandas - 分類資料的排序和分類
- Python Pandas - 分類資料的比較
- Python Pandas - 處理缺失資料
- Python Pandas - 缺失資料
- Python Pandas - 填充缺失資料
- Python Pandas - 缺失值的插值
- Python Pandas - 刪除缺失資料
- Python Pandas - 使用缺失資料進行計算
- Python Pandas - 處理重複資料
- Python Pandas - 重複資料
- Python Pandas - 計數和檢索唯一元素
- Python Pandas - 重複標籤
- Python Pandas - 分組和聚合
- Python Pandas - GroupBy
- Python Pandas - 時間序列資料
- Python Pandas - 日期功能
- Python Pandas - 時間差
- Python Pandas - 稀疏資料結構
- Python Pandas - 稀疏資料
- Python Pandas - 視覺化
- Python Pandas - 視覺化
- Python Pandas - 其他概念
- Python Pandas - 注意事項和陷阱
- Python Pandas 有用資源
- Python Pandas - 快速指南
- Python Pandas - 有用資源
- Python Pandas - 討論
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 為字串的 Series 或 DataFrame 類似的輸出。
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