pandas cut qcut 分箱算法详解

项目github地址:bitcarmanlee easy-algorithm-interview-and-practice
欢迎大家star,留言,一起学习进步

1.分箱

数据分箱的需求在实际中非常常见。对于一组连续的值,会对其切分成若干段,每一段我们将其看做一个类别,这个过程就叫做分箱。分箱操作本质上就是将连续值离散化的一个过程。

举个常见的例子:
最常见的就是对年龄进行分箱操作。假设人的年龄从0-120岁不等,我们将0-5认为是婴幼儿,6-15岁认为是少年,16-30岁认为是青年,31-50认为是中年,50-60认为是中老年,60岁以上认为是老年。在这个过程中,就将连续的年龄分为了婴幼儿、少年、青年、中年、中老年、老年这六个类别,或者说分成了六个“箱子”,每个"箱子"代表的就是一个类别。

2.cut方法

pandas里面有cut方法与qcut方法都可以实现分箱的需求,下面我们先来看看cut方法。

def t1():
    scores = [80, 55, 78, 99, 60, 35, 82, 57]
    cut = pd.cut(scores, 3)
    print(cut)

上面的方法,将scores分成三个区间,最后的结果为

[(77.667, 99.0], (34.936, 56.333], (77.667, 99.0], (77.667, 99.0], (56.333, 77.667], (34.936, 56.333], (77.667, 99.0], (56.333, 77.667]]
Categories (3, interval[float64]): [(34.936, 56.333] < (56.333, 77.667] < (77.667, 99.0]]

输出的第一行表示原来的数据位于哪个箱子,第二行表示三个箱子的相关信息。

def t2():
    scores = [80, 55, 78, 99, 60, 35, 82, 57]
    bins = [0, 60, 80, 100]
    cut = pd.cut(scores, bins)
    print(cut)

    print(cut.codes)
    print(cut.categories)
    print(pd.value_counts(cut))

输出结果为

[(60, 80], (0, 60], (60, 80], (80, 100], (0, 60], (0, 60], (80, 100], (0, 60]]
Categories (3, interval[int64]): [(0, 60] < (60, 80] < (80, 100]]
[1 0 1 2 0 0 2 0]
IntervalIndex([(0, 60], (60, 80], (80, 100]],
              closed='right',
              dtype='interval[int64]')
(0, 60]      4
(80, 100]    2
(60, 80]     2
dtype: int64

上面的方法,指定了划分的bins,所以分箱的时候区间为(0, 60), (60, 80), (80, 100)。
value_counts方法,可以统计各区间的数量。

def t3():
    scores = [80, 55, 78, 99, 60, 35, 82, 57]
    bins = [0, 60, 80, 100]
    cut = pd.cut(scores, bins, labels=["low", "mid", "high"])
    print(pd.value_counts(cut))
    print()

    cut2 = pd.cut(scores, bins, labels=["low", "mid", "high"], right=False)
    print(pd.value_counts(cut2))
low     4
high    2
mid     2
dtype: int64

high    3
low     3
mid     2
dtype: int64

上面的方法,指定了labels参数,这样每个分箱区间相当于有了标签名称。
如果指定right=False,则右区间由默认的闭区间变成开区间。

3.qcut方法

def t4():
    scores = [x**2 for x in range(11)]
    cut = pd.qcut(scores, 5)
    print(cut)
    print()
    print(pd.value_counts(cut))
[(-0.001, 4.0], (-0.001, 4.0], (-0.001, 4.0], (4.0, 16.0], (4.0, 16.0], ..., (16.0, 36.0], (36.0, 64.0], (36.0, 64.0], (64.0, 100.0], (64.0, 100.0]]
Length: 11
Categories (5, interval[float64]): [(-0.001, 4.0] < (4.0, 16.0] < (16.0, 36.0] < (36.0, 64.0] <
                                    (64.0, 100.0]]

(-0.001, 4.0]    3
(64.0, 100.0]    2
(36.0, 64.0]     2
(16.0, 36.0]     2
(4.0, 16.0]      2
dtype: int64

与cut方法不同的是,cut是按变量的值进行划分, qcut是按照变量的个数进行划分。上面方法的意思是,将输入分为数量相等的五个分箱区间。

猜你喜欢

转载自blog.csdn.net/bitcarmanlee/article/details/111408525