開始使用免費開始

分箱(Binning)數值

對於許多連續數值,你與其在乎某個欄位的精確數值,不如在乎它落在哪一個區間(bucket)。這在繪圖時或是簡化你的機器學習模型時很有用。分箱多用在精確度不是首要考量的連續變數上,例如年齡、身高、薪資。

可以使用 pd.cut(df['column_name'], bins) 來建立分箱,其中 bins 可以是整數(代表要切成等寬的區間數量),或是一個列出各區間邊界的清單。

本練習屬於課程

Feature Engineering for Machine Learning in Python

檢視課程

動手互動練習

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

# Bin the continuous variable ConvertedSalary into 5 bins
so_survey_df['equal_binned'] = ____(so_survey_df['ConvertedSalary'], ____)

# Print the first 5 rows of the equal_binned column
print(so_survey_df[['equal_binned', 'ConvertedSalary']].head())
編輯並執行程式碼