Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python/pandas循环时写入唯一的Excel工作表_Python_Excel_Pandas_Openpyxl - Fatal编程技术网

使用python/pandas循环时写入唯一的Excel工作表

使用python/pandas循环时写入唯一的Excel工作表,python,excel,pandas,openpyxl,Python,Excel,Pandas,Openpyxl,我需要阅读一张名为“输入”的Excel表格,进行一些操作,并将结果写入一张新的表格“输出”。我正在创建一个新的Pandas数据框,需要将其写入“输出”表中。我需要把这张表上的所有结果连接起来 以下是我的代码结构: import pandas as pd import math import numpy from openpyxl import load_workbook df = pd.read_excel('Test.xlsx', sheet_name="Input")

我需要阅读一张名为“输入”的Excel表格,进行一些操作,并将结果写入一张新的表格“输出”。我正在创建一个新的Pandas数据框,需要将其写入“输出”表中。我需要把这张表上的所有结果连接起来

以下是我的代码结构:

import pandas as pd
import math
import numpy
from openpyxl import load_workbook


df = pd.read_excel('Test.xlsx', sheet_name="Input")
for i in range(len(df)):
    if A:
    
        data = (...)
        # Create the pandas DataFrame 
        new_df = pd.DataFrame(data, columns = ['X','Y']) 
        print("New DF")
        print(new_df)

    elif B:

        data = (...)


         # Create the pandas DataFrame 
        new_df = pd.DataFrame(data, columns = ['X','Y']) 
        print("New DF")
        print(new_df)

    elif C:

        data = (...)

        # Create the pandas DataFrame 
        new_df = pd.DataFrame(data, columns = ['X','Y']) 
        print("New DF")
        print(new_df)

    else:
        print("WARNING")

    with pd.ExcelWriter("Test.xlsx", engine="openpyxl", mode="a") as writer:
        new_df.to_excel(writer, sheet_name="Output", index=False)
我的代码正在工作,但它创建了几个工作表Output1、Output2、Output3

我如何修复此问题,使其只有一个包含所有结果的输出表


谢谢

ExcelWriter应该放在for循环之外。尝试以下构造:

ls_new_df = []  # result container
for i in rng:
    # perform the task
    # ....
    # append new_df to list at last
    ls_new_df.append(new_df)

df_out = pd.concat(ls_new_df, axis=0)  # optional: .reset_index(drop=True)

# write to excel or csv at last
with pd.ExcelWriter("Test.xlsx", engine="openpyxl", mode="a") as writer:
    df_out.to_excel(writer, sheet_name="Output", index=False)

为什么不连接所有的数据帧并写一次呢?