Python中pd.cut()与pd.qcut()数据分箱详解
本文详细介绍Python中pandas库的pd.cut()和pd.qcut()函数在数据分箱中的应用。pd.cut用于基于指定区间的离散化,支持自定义边界和标签;pd.qcut则根据分位数生成等频箱。文章通过代码示例演示了区间开闭控制、自定义标签及精度设置等关键参数,帮助开发者掌握数据预处理中的分箱技巧。
pd.cut()函数能够实现类似成绩等级统计的功能,具体实现方式见代码示例。
假设有一组学生成绩数据,需要将其划分为不及格(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默认情况下,cut()生成的区间为左开右闭形式。若需调整区间的封闭性,可通过传递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)
2.qcut()函数用于生成指定数量的箱子,并确保每个箱子中包含相同数量的数据点。
代码示例:
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以上就是关于Python利用pd.cut()和pd.qcut()进行数据分箱操作的详细介绍。如需了解更多相关Python pd.cut()和pd.qcut()分箱操作内容,请搜索本站历史文章或继续浏览后续相关文章,感谢大家的支持!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













