You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中与R语言quantile函数type=1等价的函数是什么?

Python中等价于R quantile(type=1)的实现方法

R中的quantile(..., type=1)实现的是逆经验分布函数分位数,核心逻辑是:将数据排序后,取满足「至少p比例的数据小于等于该值」的最小元素,等价于计算排序后列表中索引为floor(p*n)的元素(n为样本量,索引从0开始)。

在Python里有几种等价实现方式:

1. 手动实现(无第三方依赖)

直接按R的type=1逻辑编写代码,适合轻量场景:

lista = [100, 200, 350, 700, 950, 275, 563]
p = 0.36

sorted_list = sorted(lista)
n = len(sorted_list)

if p == 1:
    cutoff = sorted_list[-1]
else:
    # 计算对应索引:等价于math.floor(p*n)
    index = int(p * n // 1)
    cutoff = sorted_list[index]

print(cutoff)  # 输出:275

2. 使用numpy的quantile函数

numpy的quantile函数通过method='lower'参数可直接匹配R type=1的逻辑:

import numpy as np

lista = [100, 200, 350, 700, 950, 275, 563]
cutoff = np.quantile(lista, 0.36, method='lower')

print(cutoff)  # 输出:275

3. 使用pandas的quantile函数

pandas的quantile函数通过interpolation='lower'参数实现相同效果:

import pandas as pd

lista = [100, 200, 350, 700, 950, 275, 563]
s = pd.Series(lista)
cutoff = s.quantile(0.36, interpolation='lower')

print(cutoff)  # 输出:275

以上三种方式的结果均与R中quantile(lista, 0.36, type=1)的输出完全一致。

内容的提问来源于stack exchange,提问作者Thanh Truyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 05:03:02