使用 StandardScaler() 進行置中與縮放
我們已經載入同一個名為 data 的資料集。你現在的目標是使用 sklearn 函式庫中的 StandardScaler 將它進行置中與縮放。
pandas、numpy、seaborn 與 matplotlib.pyplot 分別已以 pd、np、sns 和 plt 載入。我們也已經匯入 StandardScaler。
你可以在主控台自由探索這個資料集。
本練習屬於課程
Python 的客群分群
練習說明
- 將
StandardScaler初始化為scaler,並對data執行 fit。 - 使用
scaler對data進行縮放與置中轉換。 - 從
data_normalized建立一個 pandas DataFrame,並沿用data的索引與欄名。 - 列印摘要統計,確認平均數為 0、標準差為 1,並將結果四捨五入到小數點後 2 位。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Initialize a scaler
scaler = ____()
# Fit the scaler
____.____(data)
# Scale and center the data
data_normalized = ____.____(data)
# Create a pandas DataFrame
data_normalized = pd.DataFrame(____, index=data.index, columns=data.columns)
# Print summary statistics
print(data_normalized.____().round(____))