Ask Your Question
0

How do you add a pandas dataframe to an existing excel worksheet that already contains data?

asked 2023-04-29 12:53:16 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-04-29 13:02:01 +0000

qstack gravatar image

To add a pandas dataframe to an existing excel worksheet that already contains data, you can use the "pandas ExcelWriter" module.

Here are the steps to follow:

  1. Import the pandas ExcelWriter module:
import pandas as pd
from openpyxl import load_workbook

# set the file path
file_path = "path/to/your/excel/file.xlsx"

# load the excel workbook
book = load_workbook(file_path)

# define the sheet name where you want to add the dataframe
writer = pd.ExcelWriter(file_path, engine='openpyxl') 
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
  1. Load your dataframe:
df = pd.read_csv('path/to/your/csvfile.csv')
  1. Write the dataframe to the desired sheet:
df.to_excel(writer, sheet_name='Sheet1', startrow=3, startcol=1)
writer.save()

Note: In this example, we are adding the dataframe to Sheet1, starting from row 3 and column 1. You can change these values as per your requirement. The key point is to load the existing workbook and pass it to the pandas ExcelWriter function.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-04-29 12:53:16 +0000

Seen: 9 times

Last updated: Apr 29 '23