pandas的quantile函数
- quantile : 分位数的意思
一般为 0.25 0.5 0.75分位数 - 中数值的计算方法
- 设分位数为p : 分位数的值 = 1 + (n - 1) * p, n为数值的个数
- 看下面示例的计算
# quantile函数
DataFrame.quantile(q=0.5, axis=0, numeric_only=True, interpolation=’linear’)
- 参数意义
- q : 数字或者是类列表,范围只能在0-1之间,默认是0.5,即中位数-第2四分位数
- axis :计算方向,可以是 {0, 1, ‘index’, ‘columns’}中之一,默认为 0
- interpolation(插值方法):可以是 {‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’}之一,默认是linear。
这五个插值方法是这样的:当选中的分为点位于两个数数据点 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.
示例1 : 分位数的计算
import pandas as pd
data = pd.DataFrame({'num':[2,4,7,8,9,10]})
data
num | |
---|---|
0 | 2 |
1 | 4 |
2 | 7 |
3 | 8 |
4 | 9 |
5 | 10 |
print(data['num'].quantile()) # 默认0.5时,方法为liner
print(data['num'].quantile(interpolation="higher"))
7.5
8
-
为什么是7.5 , 8?
-
- 中位数的位置 1 + (6-1) * 0.5 = 3.5,位于第3个数和第4个数之间,分别是 7 和 8
-
- liner : 7 + (8-7) * 0.5 = 7.5, (是(8-7)*3.5的小数部分0.5 )
lower : 就是第3个数作为分位数,也就是7
height : 就是8
midpoint : (7 + 8)/ 2 = 7.5
nearest : 不晓得
-
示例2 : 直接计算多个分位数
data['num'].quantile([0.25,0.5,0.75])
0.25 4.75
0.50 7.50
0.75 8.75
Name: num, dtype: float64
numpy中的numpy.quantile
numpy.quantile(a, q, axis=None, out=None, overwrite_input=False, interpolation=‘linear’, keepdims=False)
- 其中a为想要计算分位数的数据,其他和pandas中的基本相同