Open In App

How to Append Pandas DataFrame to Existing CSV File?

Improve
Improve
Like Article
Like
Save
Share
Report

In this discussion, we’ll explore the process of appending a Pandas DataFrame to an existing CSV file using Python.

Add Pandas DataFrame to an Existing CSV File. To achieve this, we can utilize the to_csv() function in Pandas with the ‘a’ parameter to write the DataFrame to the CSV file in append mode.

Pandas DataFrame to_csv() Syntax

Syntax :

df.to_csv(‘existing.csv’, mode=’a’, index=False, header=False)

Parameters:

  • existing.csv: Name of the existing CSV file.
  • mode: By default mode is ‘w’ which will overwrite the file. Use ‘a’ to append data into the file.
  • index: False means do not include an index column when appending the new data. True means include an index column when appending the new data.
  • header: False means do not include a header when appending the new data. True means include a header when appending the new data

What is DataFrame to_csv() Function ?

The Pandas DataFrame `to_csv()` function is a method that allows you to export a DataFrame to a CSV (Comma-Separated Values) file. This function enables you to save the contents of a DataFrame into a CSV format, which is a widely used file format for tabular data. The method provides various parameters to customize the export, such as specifying the file path, choosing the delimiter, and handling missing values.

Append Pandas Dataframe to Existing CSV File

Below are the steps to Add Pandas Dataframe to an Existing CSV File.

Step 1: View Existing CSV File

First, find the CSV file in which we want to append the dataframe.  We have an existing CSV file with player name and runs, wickets, and catch done by the player. And we want to append some more player data to this CSV file. This is how the existing CSV file looks:

first-kkk

Step 2: Create New DataFrame to Append

Now let’s say we want to add more players to this CSV file. First create a dataframe of that player with their corresponding run, wicket, and catch. And make their pandas dataframe. We will append this to the existing CSV file.

Step 3: Append DataFrame to an Existing CSV File in Pandas

Let’s append the dataframe to the existing CSV file. Below is the python code.

Python3




# Append Pandas DataFrame to Existing CSV File
# importing pandas module
import pandas as pd
 
# data of Player and their performance
data = {
    'Name': ['Hardik', 'Pollard', 'Bravo'],
    'Run': [50, 63, 15],
    'Wicket': [0, 2, 3],
    'Catch': [4, 2, 1]
}
 
# Make data frame of above data
df = pd.DataFrame(data)
 
# append data frame to CSV file
df.to_csv('GFG.csv', mode='a', index=False, header=False)
 
# print message
print("Data appended successfully.")


Output :

firsty-ggg



Last Updated : 06 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads