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

如何从数据集确定四分位数(Q1/Q2/Q3)与十分位数(D1-D9)并使用Numpy实现

用Numpy计算分组数据的四分位数与十分位数

需求概述

需要完成两个计算步骤:

  • 步骤1:计算Q1、Q2、Q3(四分位数)
  • 步骤2:计算D1、D2、D3、D4、D5、D6、D7、D8、D9(十分位数)

原程序结构如下:

# Author: Evan Gertis
# Date 10/08
# program: quartiles & deciles

wages       = [250.00,259.99,260.00,269.99,270.00,279.99,280.00,289.99,290.00,299.99,300.00,309.99,310.00,319.99]
n_employees = [8,10,16,14,10,5,2]
total       = 65

def quartile(n,w,employees):
    return wages[2*n-1] + total/n - n_employees[2*n-1]/n_employees[2*n]*10

# Step 1. calculate Q1, Q2, Q3
print(quartile(2,wages,n_employees))

# Step 2. calculate D1, D2, D3, D4, D4, D5, D6, D7, D8, D9

数据集说明

为分组工资数据,每组区间对应员工数:

工资区间员工数
250.00-259.998
260.00-269.9910
270.00-279.9916
280.00-289.9914
290.00-299.9910
300.00-309.995
310.00-319.992

十分位数计算逻辑

分组数据的十分位数遵循插值公式:

对于第k个十分位数Dk,先计算位置 $ \frac{k \times N}{10} $(N为总样本数),找到该位置所在分组后,用以下公式计算:
$ D_k = L + \frac{\frac{kN}{10} - F}{f} \times w $
其中:

  • L:所在分组的下限
  • F:所在分组之前的累计频数
  • f:所在分组的频数
  • w:分组区间宽度

基于Numpy的实现代码

import numpy as np

# 整理分组数据:区间下限、每组频数
wage_lower = np.array([250.00, 260.00, 270.00, 280.00, 290.00, 300.00, 310.00])
n_employees = np.array([8, 10, 16, 14, 10, 5, 2])
total = np.sum(n_employees)  # 总员工数65
interval_width = 10.00  # 每组区间宽度固定为10

# 计算累计频数
cumulative_freq = np.cumsum(n_employees)

def calculate_quantile(quantile_ratio, total_samples, cum_freq, lower_bounds, freq, interval_w):
    """
    通用分组数据分位数计算函数
    :param quantile_ratio: 分位数比例(如Q1对应0.25,D1对应0.1)
    :param total_samples: 总样本数
    :param cum_freq: 累计频数数组
    :param lower_bounds: 分组下限数组
    :param freq: 每组频数数组
    :param interval_w: 区间宽度
    :return: 计算得到的分位数
    """
    pos = quantile_ratio * total_samples
    # 定位分位数所在分组
    group_idx = np.argmax(cum_freq >= pos)
    # 获取分组参数
    L = lower_bounds[group_idx]
    F = cum_freq[group_idx-1] if group_idx > 0 else 0
    f = freq[group_idx]
    # 应用插值公式计算
    return L + (pos - F) / f * interval_w

# Step 1: 计算四分位数
Q1 = calculate_quantile(0.25, total, cumulative_freq, wage_lower, n_employees, interval_width)
Q2 = calculate_quantile(0.5, total, cumulative_freq, wage_lower, n_employees, interval_width)
Q3 = calculate_quantile(0.75, total, cumulative_freq, wage_lower, n_employees, interval_width)
print(f"Q1: {Q1:.2f}, Q2: {Q2:.2f}, Q3: {Q3:.2f}")

# Step 2: 计算十分位数
for k in range(1, 10):
    decile = calculate_quantile(k/10, total, cumulative_freq, wage_lower, n_employees, interval_width)
    print(f"D{k}: {decile:.2f}")

代码说明

  1. 数据结构化:用Numpy数组存储分组数据,提升计算效率与可维护性
  2. 累计频数计算:通过np.cumsum快速生成累计频数,用于定位分位数所在分组
  3. 通用函数封装:将分位数计算逻辑封装为通用函数,支持四分位、十分位等任意分位数计算
  4. 公式严格适配:完全遵循分组数据的插值公式,确保结果符合统计标准

内容的提问来源于stack exchange,提问作者Evan Gertis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:25:37