python - NumPy 百分位函数不同于 MATLAB 的百分位函数

标签 python r matlab numpy percentile

当我尝试在 MATLAB 中计算第 75 个百分位数时,得到的值与在 NumPy 中得到的值不同。

MATLAB:

>> x = [ 11.308 ;   7.2896;   7.548 ;  11.325 ;   5.7822;   9.6343;
     7.7117;   7.3341;  10.398 ;   6.9675;  10.607 ;  13.125 ;
     7.819 ;   8.649 ;   8.3106;  12.129 ;  12.406 ;  10.935 ;
    12.544 ;   8.177 ]

>> prctile(x, 75)

ans =

11.3165

Python + NumPy:

>>> import numpy as np

>>> x = np.array([ 11.308 ,   7.2896,   7.548 ,  11.325 ,   5.7822,   9.6343,
     7.7117,   7.3341,  10.398 ,   6.9675,  10.607 ,  13.125 ,
     7.819 ,   8.649 ,   8.3106,  12.129 ,  12.406 ,  10.935 ,
    12.544 ,   8.177 ])

>>> np.percentile(x, 75)
11.312249999999999

我也用 R 检查了答案,我得到了 NumPy 的答案。

回复:

> x <- c(11.308 ,   7.2896,   7.548 ,  11.325 ,   5.7822,   9.6343,
+          7.7117,   7.3341,  10.398 ,   6.9675,  10.607 ,  13.125 ,
+          7.819 ,   8.649 ,   8.3106,  12.129 ,  12.406 ,  10.935 ,
+         12.544 ,   8.177)
> quantile(x, 0.75)
     75% 
11.31225 

这是怎么回事?有没有办法让 Python 和 R 的行为反射(reflect) MATLAB 的行为?

最佳答案

MATLAB 显然默认使用中点插值。 NumPy 和 R 默认使用线性插值:

In [182]: np.percentile(x, 75, interpolation='linear')
Out[182]: 11.312249999999999

In [183]: np.percentile(x, 75, interpolation='midpoint')
Out[183]: 11.3165

了解linearmidpoint 之间的区别,考虑这个简单的例子:

In [187]: np.percentile([0, 100], 75, interpolation='linear')
Out[187]: 75.0

In [188]: np.percentile([0, 100], 75, interpolation='midpoint')
Out[188]: 50.0

要编译最新版本的 NumPy(使用 Ubuntu):

mkdir $HOME/src
git clone https://github.com/numpy/numpy.git
git remote add upstream https://github.com/numpy/numpy.git
# Read ~/src/numpy/INSTALL.txt
sudo apt-get install libatlas-base-dev libatlas3gf-base
python setup.py build --fcompiler=gnu95
python setup.py install

使用 git 而不是 pip 的优点是升级(或降级)到其他版本的 NumPy 非常容易(而且您也可以获得源代码):

git fetch upstream
git checkout master # or checkout any other version of NumPy
cd ~/src/numpy
/bin/rm -rf build
cdsitepackages    # assuming you are using virtualenv; otherwise cd to your local python sitepackages directory
/bin/rm -rf numpy numpy-*-py2.7.egg-info
cd ~/src/numpy
python setup.py build --fcompiler=gnu95
python setup.py install

关于python - NumPy 百分位函数不同于 MATLAB 的百分位函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24764966/

相关文章:

python - 使用 r2PPML 将 10Mb Rdata 文件转换为 PMML 会生成 350Mb PMML 文件。我怎样才能让它变小?

matlab - 如何将符号包中的符号表达式转换为 Octave 函数?

linux - 无法读取文件 Matlab Linux Ubuntu

matlab - MATLAB 中的条件 "Or"语句

python - 试图自学 python,卡在本书的一章中,非常简单的问题

python - 如何修复 lxml 中的 XSD 导入错误?

python - 比较前一个索引处的列表

r - 使用 ggplot 命名图,由 lapply 循环

java - 如何使用 Java 运行带参数的 python 代码,./AdafruitDHT.py 22 4

r - 如何使用 ggplot2 在 R 中绘制多重响应调查项目?