R分位数参数类型为6的等价物

2024-09-30 12:18:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将Stata模型移植到Python,并在Stata的centile和Python的pandas.DataFrame.describe之间找到一些差距:

  • 斯塔塔:1%:-1657010273898333,99%:.1683179750819993
  • Python:1%:-0.1647677302502512,99:0.1607038771234249

我不知道他们是如何根据官方文件(http://www.stata.com/help.cgi?centilehttp://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.describe.html)来计算的。但当我在R中尝试相同的数据集时:

> quantile(d[, c('V1')], c(0.01, 0.99), type=5)
    1%        99% 
-0.1650828  0.1652275 
> quantile(d[, c('V1')], c(0.01, 0.99), type=6)
   1%       99% 
-0.165701  0.168318 

使用参数type=6,结果似乎与Stata相同。分位数(https://stat.ethz.ch/R-manual/R-devel/library/stats/html/quantile.html)的API文档指示以下内容:

^{pr2}$

我找不到任何具有相同实现的现有Python库。在


Tags: 文件模型httpdataframepandas官方htmlwww
2条回答

如果您想要与R的分位数相同的结果,请使用numpy.percentile

import numpy as np

np.percentile(range(1, 101), 100*(3/8))
# 38.125, same as R quantile(1:100, 3/8)

多亏了罗伯托·费勒!我编写了一个基于http://www.stata.com/manuals13/rcentile.pdf的Python函数,它产生的结果与Stata相同:

def centile(arr, percentiles=[50]):
  result = {}

  s = np.sort(arr)
  n = len(s)

  for percent in percentiles: 
    R = float(n + 1) * percent / 100
    r, f = int(R), R - int(R)

    result['{0}%'.format(percent)] = float(s[r - 1]) + f * (s[r] - s[r - 1])

  return result

相关问题 更多 >

    热门问题