四分位數與pandas中的quantile函數
1.分位數概念
統計學上的有分位數這個概念,一般用p來表示。原則上p是可以取0到1之間的任意值的。但是有一個四分位數是p分位數中較為有名的。
所謂四分位數;即把數值由小到大排列並分成四等份,處於三個分割點位置的數值就是四分位數。
為了更一般化,在計算的過程中,我們考慮p分位。當p=0.25 0.5 0.75 時,就是在計算四分位數。
- 第1四分位數 (Q1),又稱“較小四分位數”,等於該樣本中所有數值由小到大排列后第25%的數字。
- 第2四分位數 (Q2),又稱“中位數”,等於該樣本中所有數值由小到大排列后第50%的數字。
- 第3四分位數 (Q3),又稱“較大四分位數”,等於該樣本中所有數值由小到大排列后第75%的數字。
2.計算方法
1)確定p分位數的位置(有兩種方法):
方法1 pos = (n+1)*p
方法2 pos = 1+(n-1)*p(pandas 中使用的是方法2)
2)計算分位數,一般有五種方法,pandas里面的quantile函數中,interpolation參數來控制(見后)
3.quantile函數
pandas庫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.
舉例
import pandas as pd
df=pd.read_csv('data/練習.csv')
df.sort_values("Height")
|
ID |
Height |
0 |
1101 |
2 |
3 |
1201 |
4 |
2 |
1103 |
5 |
1 |
1102 |
7 |
4 |
1203 |
8 |
5 |
1205 |
12 |
參數q默認為0.5(中位數)
df['Height'].quantile()
6.0
參數interpolation的不同方法
df['Height'].quantile(q=0.5,interpolation="linear")
6.0
df['Height'].quantile(q=0.5,interpolation="lower")
5
df['Height'].quantile(q=0.5,interpolation="higher")
7
df['Height'].quantile(q=0.5,interpolation="midpoint")
6.0
df['Height'].quantile(q=0.5,interpolation="nearest")
5
說明:df['Height']中一共有6個數據,中位數的位置pos=1+(6-1)*0.5=3.5,這個位置介於5和7之間,則i=5,j=7,fraction=0.5
- linear:i + (j - i) * fraction=5+(7-5)*0.5=6
- lower:i=5
- higher:j=7
- midpoint:(i+j)/2=(5+7)/2=6
- nearest:5更接近(這個沒太搞懂,貌似是fraction更靠近的那個整數)
參數q為列表類型,計算四分位數
df['Height'].quantile([0.25,0.5,0.75])
0.25 4.25
0.50 6.00
0.75 7.75
Name: Height, dtype: float64