Home > Backend Development > Python Tutorial > How to Append a Pandas DataFrame to an Existing Excel Sheet Without Overwriting?

How to Append a Pandas DataFrame to an Existing Excel Sheet Without Overwriting?

Susan Sarandon
Release: 2024-12-19 04:21:09
Original
1023 people have browsed it

How to Append a Pandas DataFrame to an Existing Excel Sheet Without Overwriting?

Append an Existing Excel Sheet with a New Dataframe Using Python Pandas

In this scenario, the code provided is designed to iterate through a folder containing Excel files, apply specific data transformations to each file, and then append the modified data to an existing central Excel file ('master_data.xlsx'). However, the current implementation overwrites the existing 'master_data.xlsx' each time it is executed. The goal is to append the new data to the bottom of the existing Excel sheet without overwriting it.

To achieve this, a solution is needed that can access the existing 'master_data.xlsx' file, merge the new data into it, and save it without overwriting the original content. Here's how it can be accomplished:

1. Import Pandas and OpenPyxl:

import pandas as pd
import openpyxl
Copy after login

2. Load the Existing 'master_data.xlsx' File:

master_data = pd.read_excel('master_data.xlsx')
Copy after login

3. Iterate Through the New Dataframes:

for data in dfList:
    # Append the new data to the existing dataframe
    master_data = master_data.append(data)
Copy after login

4. Save the Updated 'master_data.xlsx' File:

master_data.to_excel('master_data.xlsx', index=False)
Copy after login

This updated approach maintains the existing contents of 'master_data.xlsx' and appends the new data to the bottom of the sheet.

The above is the detailed content of How to Append a Pandas DataFrame to an Existing Excel Sheet Without Overwriting?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template