cut()
定义:cut返回 x 中的每一个数据在bins中对应的范围。根据值本身来选择箱子均匀间隔,即每个箱子的间距都是相同的。
语法:
pandas.cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_lowest=False)
参数:
- x : 必须是一维数据
- bins: 不同面元(不同范围)类型:整数,序列如数组, 和IntervalIndex
- right: 最后一个bins是否包含最右边的数据,默认为True
- precision:精度 默认保留三位小数
- retbins: 即return bins 是否返回每一个bins的范围 默认为False
例子:实现成绩的优良差统计
import numpy as np
import pandas as pd
scores = np.random.uniform(0,100,size=30).astype('int')
# 指定分箱的区间
grades = [0,59,70,85,100]
boxs = pd.cut(scores,grades)
boxs.value_counts()
#output:
(0, 59] 16
(59, 70] 1
(70, 85] 5
(85, 100] 8
dtype: int64
# 传入label来自定义箱名
group_names = ['不及格','及格','良','优秀']
boxs= pd.cut(scores,grades,labels=group_names)
boxs.value_counts()
#output:
不及格 16
及格 1
良 5
优秀 8
dtype: int64
# 将成绩均匀的分在四个箱子中,precision=2的选项将精度控制在两位
boxs = pd.cut(scores,4,precision=2)
boxs.value_counts()
#output:
(2.91, 26.5] 6
(26.5, 50.0] 6
(50.0, 73.5] 5
(73.5, 97.0] 13
dtype: int64
qcut()
定义:qcut是根据这些值的频率来选择箱子的均匀间隔,每个箱子中含有的数的数量是相同的。
语法:
pandas.qcut(x, q, labels=None, retbins=False, precision=3, duplicates=’raise’)
参数:
- x: 是数据ndarray或Series
- q:整数或分位数数组;定义区间分割方法
分位数10为十分位数,4为四分位数等。或分位数组,如四分位数 [0, 0.25, 0.5, 0.75, 1] 分成两半[0, 0.5, 1]
例子:将成绩平均分为四份/按照四分位对成绩划分
scores = np.random.uniform(0,100,size=40).astype('int')
# 平分四组数
boxs = pd.qcut(scores,4)
boxs.value_counts()
#output:
(0.999, 23.75] 10
(23.75, 55.0] 10
(55.0, 76.5] 10
(76.5, 99.0] 10
dtype: int64
# 设定label
boxs = pd.qcut(scores,4,labels=['s1','s2','s3','s4'])
boxs.value_counts()
#output:
s1 10
s2 10
s3 10
s4 10
dtype: int64
# 设定等分位分箱
boxs = pd.qcut(scores,[0, 0.1, 0.2, 0.3, 1])
boxs.value_counts()
# output:
(0.999, 13.8] 4
(13.8, 22.6] 4
(22.6, 30.6] 4
(30.6, 99.0] 28
dtype: int64
#输出元祖
boxs = pd.qcut(scores,[0, 0.1, 0.2, 0.3, 1],labels=['s1','s2','s3','s4'],retbins=True)
boxs[0].value_counts()
#output:
s1 4
s2 4
s3 4
s4 28
dtype: int64
本文详细介绍了pandas中的cut()和qcut()函数。cut()根据值的区间进行均匀间隔划分,而qcut()则依据值的频率进行等频划分。通过实例展示了如何使用这两个函数进行数据分段,例如对成绩进行优良差统计和四分位数划分。
398

被折叠的 条评论
为什么被折叠?



