How to add pandas DataFrame to an existing CSV file?

Given a Pandas DataFrame, we have to add it to an existing CSV file. By Pranit Sharma Last updated : September 22, 2023

File handling is the process of creating, reading, updating, and deleting a file with some content into the memory of the computer system. While dealing with pandas DataFrames, we save these DataFrames in the form of the CSV file, sometimes we need to make changes to these existing CSV files.

Problem statement

Given a Pandas DataFrame, we have to add it to an existing CSV file.

Adding pandas DataFrame to an existing CSV file

In that case, the concept of file handling plays an important role. To add pandas DataFrame to an existing CSV file, we need to open the CSV file in append mode and then we can add the DataFrame to that file with the help of pandas.DataFrame.to_csv() method.

Note

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

Python program to add pandas DataFrame to an existing CSV file

# Importing pandas package
import pandas as pd

#  Creating a dictionary
d= {'E':[20,20,30,30]}

# Creating a DataFrame
df = pd.DataFrame(d)

data = pd.read_csv('D:/mycsv1.csv')

# Display old file
print("old csv file\n",data,"\n")

# Opening csv file in append mode and 
# adding new dataframe
with open('D:/mycsv1.csv', 'a') as f:
    df.to_csv(f, header=False)
    print("Success")

# Reading file again
data = pd.read_csv('D:/mycsv1.csv')

# Display modified file
print("Modified File:\n",data)

Output

The output of the above program is:

Example 1: Add pandas DataFrame

After, adding new DataFrame in this existing file,

Example 2: Add pandas DataFrame

After, reading this file again:

Example 3: Add pandas DataFrame

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.