【问题标题】:Equivalent of R quantile with parameter type=6参数类型 = 6 的 R 分位数的等价物
【发布时间】:2015-11-19 15:56:26
【问题描述】:

我正在尝试将 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相同。分位数的 API 文档 (https://stat.ethz.ch/R-manual/R-devel/library/stats/html/quantile.html) 指出以下内容:

Type 6
     m = p. p[k] = k / (n + 1). Thus p[k] = E[F(x[k])]. This is used by Minitab and by SPSS.

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

【问题讨论】:

标签: python r pandas statistics stata


【解决方案1】:

感谢罗伯托·费雷尔!我编写了一个基于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

【讨论】:

  • 这给出了与 R 分位数不同的结果 :)
【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多