Sunday, September 22, 2024
Google search engine
HomeLanguagesHow to Append Pandas DataFrame to Existing CSV File?

How to Append Pandas DataFrame to Existing CSV File?

In this article, we will discuss how to append Pandas  dataframe to the existing CSV file using Python.

Appending dataframe means adding data rows to already existing files. To add a dataframe row-wise to an existing CSV file, we can write the dataframe to the CSV file in append mode by the parameter a using the pandas to_csv() function.

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.

Stepwise Implementation

Below are the steps to Append Pandas DataFrame to 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:

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 Existing CSV File

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:

RELATED ARTICLES

Most Popular

Recent Comments