記錄用:
一.等距分箱/等寬分箱
1.概念:將變量的取值范圍分為k個等寬的區(qū)間,每個區(qū)間當作一個分箱。
2.方法
數學運算:通過向上取整ceil() 和 向下取整floor()
-- 對col進行0.1寬度的分箱
select col, ceil(col*10)/10 as group1, floor(col*10)/10 as group2
from(
select stock(5, 0.1, 0.15, 0.20, 0.25, 0.3) as col
) as a
result
二.等頻分箱
1.概念:把觀測值按照從小到大的順序排列,根據觀測的個數等分為k部分,每部分當作一個分箱,即百分位數的概念。
2.方法
Ntile(n) over(order by col):分塊函數
備注:NULL值的處理,是否需要單獨為1組。
select col
-- NULL默認為最小值
, ntile(2) over( order by col) as group1
-- 將NULL單獨為1組
, if(col is null, null, ntile(2) over( partition by if(col is null, 1, 0) order by col) as group2
from(
select cast(col as int) as col
from(
select stack(5, 'NULL', '1', '2', '3', '4') as col
) as a
) as a