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.
df.to_csv(‘existing.csv’, mode=’a’, index=False, header=False)
- 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.
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.