Python学习笔记:利用pd.quantile实现分位数统计

您所在的位置:网站首页 python怎么计算位数 Python学习笔记:利用pd.quantile实现分位数统计

Python学习笔记:利用pd.quantile实现分位数统计

2024-01-21 16:03| 来源: 网络整理| 查看: 265

一、p分位数概念

原则上p是可以取0-1之间的任意值,四分位数是p分位数中较为有名的。

所谓四分位数:即把数值由小到大排列并分成四等份,处于三个分割点位置的数值就是四分位数。

第1四分位数 (Q1):又称“较小四分位数”,等于该样本中所有数值由小到大排列后第25%的数字 第2四分位数 (Q2):又称“中位数”,等于该样本中所有数值由小到大排列后第50%的数字 第3四分位数 (Q3):又称“较大四分位数”,等于该样本中所有数值由小到大排列后第75%的数字

第3四分位数与第1四分位数的差距又称四分位距(InterQuartile Range, IQR)

二、pandas中quantile函数

quantile() 函数语法为:

DataFrame.quantile(q=0.5, axis=0, numeric_only=True, interpolation='linear')

参数解释:

q -- 浮点数或者数组,默认值0.5,取中位数(0 ≤ q ≤ 1) axis -- 行或列,默认为0,取值为:{0, 1, ‘index’, ‘columns’} 0 or ‘index’ -- 行 1 or ‘columns’ -- 列 interpolation -- 插值方法,取值为:{‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’} 当选中的分位点位于两个数数据点 i and j 之间时: linear: i + (j - i) * fraction, fraction由计算得到的pos的小数部分 lower: i. higher: j. nearest: i or j whichever is nearest. midpoint: (i + j) / 2. 三、实例 # 测试数据 df = pd.DataFrame(np.array([[1, 1], [2, 10], [3, 100], [4, 100]]),columns=['a', 'b']) ''' a b 0 1 1 1 2 10 2 3 100 3 4 100 ''' # 0.1分位数 df.quantile(0.1) a 1.3 b 3.7 Name: 0.1, dtype: float64 # 0.5分位数(中位数) df.quantile(0.5) a 2.5 b 55.0 Name: 0.5, dtype: float64 # 测试数据 age sex 0 54.0 男 1 39.0 男 2 59.0 男 3 59.0 男 4 52.0 男 # 求分位数 data.age.quantile([0.25, 0.5, 0.75]) 0.25 35.0 0.50 45.0 0.75 54.0 Name: age, dtype: float64 四、应用

在数据清洗过程中,可以利用分位数实现对异常数据的剔除。

盖帽法 # 盖帽法 def blk(floor, root): def f(x): if x < floor: x = floor elif x > root: x = root return x return f 清洗 data["col"] = data["col"].map(blk(0, root=data["col"].quantile(0.99))) 缺失值填充 data["col"] = data["col"].fillna(0)

注意,需先通过盖帽法完成异常数据清洗后,再进行缺失值填充。

参考链接1:pandas中的quantile函数

参考链接2:p分位函数(四分位数)概念与pandas中的quantile函数



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3