Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append pandas dataframe to excelsheet, not overwrite it

I want to append the contents of a panda dataframe df to an excelsheet.

This is what I did;

df.to_excel(excel_writer="target.xlsx", sheet_name="sheet_1")

The problem with this code is that it overwrites target.xlsx. I lost all my old data in target.xlsx as a result. What I want the code to do is to append, not overwrite the excel sheet.

I am using python 3.7.

like image 507
guagay_wk Avatar asked Dec 06 '22 09:12

guagay_wk


2 Answers

with pd.ExcelWriter('target.xlsx', mode='a') as writer:  
    df.to_excel(writer, sheet_name='sheet_1')

Source: Pandas Dataframe to Excel

like image 76
kaushik karan Avatar answered Dec 10 '22 10:12

kaushik karan


I think the easiest way to do this is:

import pandas as pd
import numpy as np
import xlsxwriter

workbook = xlsxwriter.Workbook('arrays.xlsx')
worksheet = workbook.add_worksheet() # a created excel sheet

array = pd.read_csv('array.csv')
array = array.tolist()

row = 0

for col, data in enumerate(array):
    worksheet.write_column(row, col, data)

workbook.close()

Here is the xlsxwriter documentation.

like image 44
Fateh Avatar answered Dec 10 '22 11:12

Fateh