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

Python将Gambler's Ruin蒙特卡洛模拟结果按n行分组输出CSV新列

你的代码存在两个核心问题:

  1. 每次生成单条蒙特卡洛模拟结果时都新建了仅包含当前数据的DataFrame,没有累计存储所有10000条结果
  2. 调用df.to_csv()时使用默认覆盖写入模式,每次执行都会清空之前的文件内容,所以最终只保留了最后一条结果
完整实现代码
import pandas as pd

# 配置参数
GROUP_SIZE = 100  # 每组100行
TOTAL_MC = 10000  # 总模拟次数

# 第一步:累计存储所有模拟结果
all_results = []
for i in range(TOTAL_MC):
    # 这里替换为你自己的Gambler's Ruin模拟逻辑,得到最终money
    # ---------------你的模拟逻辑开始---------------
    import random
    money = 10 if random.random() > 0.5 else 0  # 示例模拟逻辑,替换为你自己的实现
    # ---------------你的模拟逻辑结束---------------
    all_results.append({"MC Point": i, "Outcome": money})

# 转成完整DataFrame
df_full = pd.DataFrame(all_results)

# 第二步:格式化内容为要求的字符串格式
df_full["content"] = df_full.apply(lambda row: f"MC = {row['MC Point']} Outcome = {row['Outcome']}", axis=1)

# 第三步:按每GROUP_SIZE行分组,每组转为新列
groups = [group["content"].reset_index(drop=True) for _, group in df_full.groupby(df_full.index // GROUP_SIZE)]
result_df = pd.concat(groups, axis=1)

# 导出CSV,不需要列名可保留header=False,需要列名删除该参数即可
result_df.to_csv("output.csv", index=False, header=False)

补充说明

如果需要自定义列名,可以在concat生成result_df后添加如下代码修改列名:

result_df.columns = [f"第{i+1}组" for i in range(len(result_df.columns))]

内容的提问来源于stack exchange,提问作者Klaus Müller

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:18:03