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
相关产品推荐
相关产品推荐

