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

如何编写函数获取多参数的Bootstrap均值与中位数估计

多参数Bootstrap估计函数实现方案

我已经实现了针对单一参数的Bootstrap估计函数,代码如下:

def get_boostrap_estimates_single_param(sample_size):
    """
    生成Bootstrap样本,函数内部硬编码数据集路径以适配后续Pool.map()调用
    :param sample_size: Bootstrap样本的行数
    :returns: 该样本的均值和中位数
    """
    dataPath = '/home/faustus/Documents/Review Courses/Big Data Analysis/age.csv'
    age = pd.read_csv(dataPath, index_col = False)
    
    # 打乱原数据集
    df = pd.DataFrame.sample(age, n = age.size)
    # 抽取带替换的Bootstrap样本
    df_sample = df.sample(sample_size, replace = True)
    
    return df_sample.mean(), df_sample.median()

该函数调用示例及输出:

get_boostrap_estimates_single_param(2000)
(age    23.057
 dtype: float64,
 age    19.0
 dtype: float64)

针对需要传入DataFrame并支持多参数的Bootstrap估计函数,以下是具体实现:

import pandas as pd

def get_boostrap_estimates_multiple_params(df, sample_size):
    """
    生成Bootstrap样本并计算各参数的均值和中位数
    :param df: 输入数据集(DataFrame格式)
    :param sample_size: Bootstrap样本的行数
    :returns: 元组,包含各参数的均值Series和中位数Series
    """
    # 抽取带替换的Bootstrap样本
    # 注:原单参数函数中的打乱步骤可省略,因为带替换采样本身具有随机性,不影响结果
    df_sample = df.sample(n=sample_size, replace=True)
    
    # pandas会自动按列计算所有参数的均值和中位数
    sample_means = df_sample.mean()
    sample_medians = df_sample.median()
    
    return sample_means, sample_medians

关键说明:

  • 移除了硬编码的数据集加载逻辑,直接使用传入的df参数,兼容任意列数的DataFrame
  • 无需手动循环列:pandas的mean()和median()方法会对DataFrame的每一列独立计算统计量,返回的Series会保留原列名作为索引
  • 若坚持要保留原单参数函数中的打乱步骤,可在采样前添加:df_shuffled = df.sample(n=len(df)),再基于df_shuffled执行sample()操作,这不会改变Bootstrap的统计特性

测试示例:

假设输入包含age和income两列的DataFrame:

test_df = pd.DataFrame({
    'age': [18, 20, 22, 25, 30]*200,
    'income': [3000, 4000, 5000, 6000, 8000]*200
})

# 调用函数
mean_result, median_result = get_boostrap_estimates_multiple_params(test_df, 2000)
print("均值结果:\n", mean_result)
print("中位数结果:\n", median_result)

输出示例:

均值结果:
 age      23.015
 income    5195.0
 dtype: float64
中位数结果:
 age      22.0
 income    5000.0
 dtype: float64

内容的提问来源于stack exchange,提问作者Maale Faustus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:46:08