函数原型markdown
DataFrame.quantile(q=0.5, axis=0, numeric_only=True, interpolation=’linear’)函数
参数post
- q : float or array-like, default 0.5 (50% quantile 即中位数-第2四分位数) 0 <= q <= 1, the quantile(s) to compute - axis : {0, 1, ‘index’, ‘columns’} (default 0) 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wise - interpolation(插值方法) : {‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’} 当选中的分为点位于两个数数据点 i and j 之间时: linear: i + (j - i) * fraction, fraction由计算获得的pos的小数部分(能够经过下面一个例子来理解这个fraction); lower: i. higher: j. nearest: i or j whichever is nearest. midpoint: (i + j) / 2.
原则上p是能够取0到1之间的任意值的。可是有一个四分位数是p分位数中较为有名的。测试
所谓四分位数;即把数值由小到大排列并分红四等份,处于三个分割点位置的数值就是四分位数。ui
第3四分位数与第1四分位数的差距又称四分位距(InterQuartile Range,IQR)lua
为了更通常化,在计算的过程当中,咱们考虑p分位。当p=0.25 0.5 0.75 时,就是在计算四分位数。spa
首先肯定p分位数的位置(有两种方法):rest
方法1 pos = (n+1)*p
方法2 pos = 1+(n-1)*pcode
pandas 中使用的是方法2肯定的。server
给定测试数据:
a b 0 1 1 1 2 10 2 3 100 3 4 100
计算
df = pd.DataFrame(np.array([[1, 1], [2, 10], [3, 100], [4, 100]]),columns=['a', 'b']) print(df.quantile(.1))
结果是:
a 1.3 b 3.7 Name: 0.1, dtype: float64
默认使用的是linear 插值
计算a列
pos = 1 + (4 - 1)*0.1 = 1.3
fraction = 0.3
ret = 1 + (2 - 1) * 0.3 = 1.3
计算b列
pos = 1.3
ret = 1 + (10 - 1) * 0.3 = 3.7
在b中,假如pos等于2.5呢,即在2-3之间,那i对应就是10,j对应就是100,ret = 10 + (100-10) * 0.3 = 55
“分为点p位于两个数数据点 i and j 之间时”,好比 y= [1,10,100,100],x= [0,1,2,3],对应于[0,0.333,0.667,1],当p=0.4时,i、j分别为十、100,所以,pos = 1 + (4-1)*0.4=2.2,pos取小数部分即0.2,也即fraction=0.2(fraction由计算获得的pos的小数部分),,,故值为10+(100-10)* 0.2=28 。 验证: df = pd.DataFrame(np.array([[1, 1], [2, 10], [3, 100], [4, 100]]),columns=['a', 'b']) print df.quantile([0.1,0.2,0.4,0.5, 0.75])