我有一个非常简单的数据框:
df = pd.DataFrame([5,7,10,15,19,21,21,22,22,23,23,23,23,23,24,24,24,24,25], columns=['val'])
df.median()= 23这是正确的,因为从列表中的19个值,23是第10个值(23个之前的9个值,23之后的9个值)
我试图将第1和第3四分位数计算为:
df.quantile([.25, .75])
val
0.25 20.0
0.75 23.5
我原本预计,从中位数的9个值开始,第一个四分位数应该是19,但正如你可以看到的那样,python表示它是20.同样,对于第3个四分位数,从右到左的第5个数字是24,但是python显示为23.5。
大熊猫如何计算四分位数?
它默认使用线性插值。以下是如何使用最近的:
df['val'].quantile([0.25, 0.75], interpolation='nearest')
Out:
0.25 19
0.75 24
有关interpolation
参数如何工作的官方文档的更多信息:
This optional parameter specifies the interpolation method to use,
when the desired quantile lies between two data points `i` and `j`:
* linear: `i + (j - i) * fraction`, where `fraction` is the
fractional part of the index surrounded by `i` and `j`.
* lower: `i`.
* higher: `j`.
* nearest: `i` or `j` whichever is nearest.
* midpoint: (`i` + `j`) / 2.
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.quantile.html