0

I have an excel file (df2) and i have used for loop to it to get multiple outputs and then i want to append all the multiple outputs obtained for that file so that i can get it into one single excel. Please find my code below and suggest some ideas so that i can complete my code.

import os
from os import path
import pandas as pd

src = "C:\\ASPAIN-ORANGE\\test_wind3\\udc\\folder\\"

df = pd.read_excel('check_.xlsx',sheet_name='Align_pivot')
files = [i for i in os.listdir(src) if i.startswith("_Verification_") and path.isfile(path.join(src, i))]
for f in files:
    slice1 = 19
    file_slice = f[slice1:].replace(".csv", "")
    df1 = pd.read_csv(f)
    total_rows_df1 = len(df1.axes[0])
    df2 = df[df['MO'] == (file_slice)]
    total_rows_df2 = sum(df2.To_Align)
    print("filename : "+str(file_slice))
    print("Number of Rows_df1: "+str(total_rows_df1))
    print("Number of Rows_df2: "+str(total_rows_df2))
    if total_rows_df1 == total_rows_df2:
        print('True')
    else:
        print('False')
    df2.to_excel('output.xlsx', index=False, na_rep = 'NA', header = True)

1st Iteration output

2nd Iteration output

3rd Iteration output

and so on

Final appended Output

Your kind help would really be appreciated.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Does this answer your question? [Append existing excel sheet with new dataframe using python pandas](https://stackoverflow.com/questions/38074678/append-existing-excel-sheet-with-new-dataframe-using-python-pandas) – Rohit Chauhan Jan 24 '20 at 12:38
  • Not actually. As I need the output obtained with each iteration to be appended one below other. Suppose I got output 'apple' in 1st iteration, 'banana' in 2nd iteration and 'mango' in 3rd iteration. Then i want [apple, banana, mango] as output in excel without overwriting any of them. I am giving an excel example as well. – Nidhi Bakshi Jan 24 '20 at 13:17

1 Answers1

0

You can use DataFrame.append method (Append rows of other to the end of caller, returning a new object):

df = df.append(sheet, ignore_index=True)

Once all rows are added you can call to_excel method to write the excel.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html

Milos K
  • 1,009
  • 8
  • 5
  • This doesn't solve my problem. As i want the output obtained from loop to be appended. For example: if i got output [1] from 1st run of loop and [2] from second run of loop, [3] from third run of loop and so on. Then my output should be [1,2,3] in an excel and it should not overwrite the 1st or second output. Remember I have data in excel. – Nidhi Bakshi Jan 24 '20 at 13:06