How to add pandas DataFrame to an existing CSV file?

Given a Pandas DataFrame, we have to add it to an existing CSV file.
Submitted by Pranit Sharma, on June 07, 2022

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.

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.

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,

# 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")

Output:

Example 1: Add pandas DataFrame

Now, adding new DataFrame in this existing file,

# 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")

Output:

Example 2: Add pandas DataFrame

We can also read this file again,

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

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

Output:

Example 3: Add pandas DataFrame

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




© https://www.includehelp.com some rights reserved.