假如我们有一组学生成绩,我们需要将这些成绩分为不及格(0-59)、及格(60-70)、良(71-85)、优(86-100)这几组。这时候可以用到cut()
import numpy as np
import pandas as pd
# 我们先给 scores传入30个从0到100随机的数
scores = np.random.uniform(0,100,size=30)
# 然后使用 np.round()函数控制数据精度
scores = np.round(scores,1)
# 指定分箱的区间
grades = [0,59,70,85,100]
cuts = pd.cut(scores,grades)
print('\nscores:')
print(scores)
print('\ncuts:')
print(cuts)
# 我们还可以计算出每个箱子中有多少个数据
print('\ncats.value_counts:')
print(pd.value_counts(cuts))
======output:======
scores:
[ 6. 50.8 80.2 22.1 60.1 75.1 30.8 50.8 81.6 17.4 13.4 24.3 67.3 84.4
63.4 21.3 17.2 3.7 40.1 12.4 15.7 23.1 67.4 94.8 72.6 12.8 81. 82.
70.2 54.1]
cuts:
[(0, 59], (0, 59], (70, 85], (0, 59], (59, 70], ..., (0, 59], (70, 85], (70, 85], (70, 85], (0, 59]]
Length: 30
Categories (4, interval[int64]): [(0, 59] < (59, 70] < (70, 85] < (85, 100]]
cuts.value_counts:
(0, 59] 17
(70, 85] 8
(59, 70] 4
(85, 100] 1
dtype: int64
默认情况下,cat()的区间划分是左开右闭,可以传递right=False来改变哪一边是封闭的
代码示例:
cuts = pd.cut(scores,grades,right=False)
也可以通过向labels选项传递一个列表或数组来传入自定义的箱名
代码示例:
group_names = ['不及格','及格','良','优秀']
cuts = pd.cut(scores,grades,labels=group_names)
当我们不需要自定义划分区间时,而是需要根据数据中最大值和最小值计算出等长的箱子。
代码示例:
# 将成绩均匀的分在四个箱子中,precision=2的选项将精度控制在两位
cuts = pd.cut(scores,4,precision=2)
代码示例:
import numpy as np
import pandas as pd
# 正态分布
data = np.random.randn(100)
# 分四个箱子
cuts = pd.qcut(data,4)
print('\ncuts:')
print(cuts)
print('\ncuts.value_counts:')
print(pd.value_counts(cuts))
======output:======
cuts:
[(-0.745, -0.0723], (0.889, 2.834], (-0.745, -0.0723], (0.889, 2.834], (0.889, 2.834], ..., (-0.745, -0.0723], (-0.0723, 0.889], (-3.1599999999999997, -0.745], (-0.745, -0.0723], (-0.0723, 0.889]]
Length: 100
Categories (4, interval[float64]): [(-3.1599999999999997, -0.745] < (-0.745, -0.0723] < (-0.0723, 0.889] <
(0.889, 2.834]]
cuts.value_counts:
(0.889, 2.834] 25
(-0.0723, 0.889] 25
(-0.745, -0.0723] 25
(-3.1599999999999997, -0.745] 25
dtype: int64