I have a dataframe with certain variables. When I print the dataframe within the loop, I see all the different rows of data. But when I try to write this data into a spreadsheet on Excel, only the last row is written.
file1r = open("Catastrophe Reinsurance.txt","r")
lines_counter_18 = 1
for line in file1r:
line = line.rstrip("\n")
if lines_counter_18 > 9:
year = line[0:4]
year_2013 = line[7:18]
year_2014 = line[21:32]
year_2015 = line[35:46]
year_2016 = line[49:60]
year_2017 = line[63:74]
year_2018 = line[77:88]
df_1r = pd.DataFrame({'year':year,'year_2013':year_2013,'year_2014':year_2014,'year_2015':year_2015,'year_2016':year_2016,'year_2017':year_2017,'year_2018':year_2018},index=[0])
#print(df_1r)
lines_counter_18 += 1
df_1r.to_excel(writer,sheet_name='Catastrophe Reinsurance',index=True)
I define the writer outside of the loop as :
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
I save the workbook outside of the loop as well. The looping logic does not seem to work since only the last row is written to the sheet. Am I missing something?