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

Pandas DataFrame行随机打乱后导出15次Excel仅得到1个输出求助

Pandas 随机打乱保存问题解决方案

错误原因

  • 你写的randomize()函数内部的df_shuffled属于局部变量,仅在函数内部生效,循环调用15次都不会修改函数外部定义的df_shuffled变量
  • Excel保存逻辑写在循环体外,且使用固定文件名,运行后只会生成1个被最后一次赋值覆盖的结果文件

修正后代码

import pandas as pd

# 构造初始DataFrame
sales_to_do = {'Task': ['Call with the client', 'Preparing for the calls', 'Training staff',
                    'Daily tasks (Emails, questions, chasing)'],
           'Type of task': ['Call (external - new lead)', 'Preparing communication with leads', 'Training',
                            'Call (external - new lead)']}
df = pd.DataFrame(sales_to_do)

def randomize():
    # 直接返回打乱后的DataFrame
    return df.sample(frac=1)

# 循环执行15次打乱+保存
for i in range(15):
    df_shuffled = randomize()
    # 文件名按序号命名,避免覆盖
    save_path = fr'C:\Users\Alex\Desktop\Output{i+1}.xlsx'
    df_shuffled.to_excel(save_path, index=False, header=True)

可选优化

如果需要固定每次打乱的结果、方便复现,可以给sample方法加random_state参数:

return df.sample(frac=1, random_state=i)

内容的提问来源于stack exchange,提问作者Alexey Podoynitsyn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 17:21:02