You need to enable JavaScript to run this app. 如何通过for range循环完成20次DataFrame抽样并计算各列均值
优惠活动
大模型
产品
解决方案
定价
更多

如何通过for range循环完成20次DataFrame抽样并计算各列均值

适配现有代码的20次抽样+列均值计算实现

你现有逻辑已经完成了数据读取、截取最后8列的前置处理,只需要通过循环扩展抽样逻辑即可,全程不需要改动原有核心抽取规则,只需要注意修正循环内的随机种子设置(否则20次抽样会完全重复,没有实际意义)。

  • 前置保留原有基础代码逻辑:
import pandas as pd
df = pd.read_csv(filename)
df1 = df.iloc[:, -8:]
  • 循环实现的核心逻辑:
    1. 初始化存储容器,避免无意义的内存占用
    2. 循环20次执行抽样,用循环序号作为每次的随机种子,保证抽样独立
    3. 循环结束后聚合所有结果,计算各列最终均值
  • 完整可运行代码:
# 存储每次抽样的列均值结果
mean_records = []
for round_idx in range(20):
    # 每次用循环序号作为随机种子,保证抽样结果独立
    current_sample = df1.sample(10, replace=True, random_state=round_idx)
    # 记录当前样本的列均值
    mean_records.append(current_sample.mean())
# 汇总计算20次抽样的整体列均值
final_result = pd.DataFrame(mean_records).mean()

实操注意事项:

  • 如果你需要留存20份抽样的原始行数据,只需要把每次的current_sample存入列表,最后拼接后计算均值即可,不需要额外修改抽取规则:
    all_samples = []
    for round_idx in range(20):
        current_sample = df1.sample(10, replace=True, random_state=round_idx)
        all_samples.append(current_sample)
    final_result = pd.concat(all_samples).mean()
    
  • 不要在循环里固定使用random_state=0,否则20次循环会抽取完全相同的10行样本,整个抽样流程和单次抽样没有区别。

内容的提问来源于stack exchange,提问作者Alex Fernando

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.01 08:06:03