開始使用免費開始

交易資料的 one-hot 編碼

在整門課中,我們會使用一個通用的前處理流程來準備進行 market basket analysis 的資料。第一步是匯入一個 pandas DataFrame,並選取包含交易紀錄的欄位。該欄位中的每筆交易是一個字串,裡面包含多個品項,彼此以逗號分隔。下一步是使用 lambda 函式把每筆交易字串切分成清單,將該欄位轉換為由多個清單組成的清單。

在這個練習中,你會從雜貨資料集的「清單的清單」開始,該物件以 transactions 提供給你。接著你會把 transactions 轉換為 one-hot 編碼的 DataFrame,其中每個欄位由 TRUEFALSE 組成,用來表示某個品項是否出現在該筆交易中。

本練習屬於課程

Python 的 Market Basket Analysis

檢視課程

練習說明

  • mlxtend.preprocessing 匯入 TransactionEncoder
  • 產生一個交易編碼器,並在 transactions 中辨識唯一的品項。
  • transactions 進行 one-hot 編碼為陣列,並將其值指定給 onehot
  • 使用品項名稱作為欄名,將該陣列轉換成 pandas DataFrame。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Import the transaction encoder function from mlxtend
from ____.____ import ____
import pandas as pd

# Instantiate transaction encoder and identify unique items in transactions
encoder = TransactionEncoder().____(____)

# One-hot encode transactions
onehot = encoder.____(transactions)

# Convert one-hot encoded data to DataFrame
onehot = pd.DataFrame(____, columns = encoder.columns_)

# Print the one-hot encoded transaction dataset
print(onehot)
編輯並執行程式碼