Concatenate pandas DataFrame to Existing CSV File in Python (Example Code)
In this tutorial, I’ll explain how to append a new pandas DataFrame to an existing CSV file in Python.
Setting up the Example
import pandas as pd # Import pandas library |
import pandas as pd # Import pandas library
my_df = pd.DataFrame({'A':range(0, 5), # Construct pandas DataFrame in Python 'B':['x', 'y', 'x', 'x', 'y'], 'C':range(15, 10, - 1)}) print(my_df) # A B C # 0 0 x 15 # 1 1 y 14 # 2 2 x 13 # 3 3 x 12 # 4 4 y 11 |
my_df = pd.DataFrame({'A':range(0, 5), # Construct pandas DataFrame in Python 'B':['x', 'y', 'x', 'x', 'y'], 'C':range(15, 10, - 1)}) print(my_df) # A B C # 0 0 x 15 # 1 1 y 14 # 2 2 x 13 # 3 3 x 12 # 4 4 y 11
my_df.to_csv('my_df.csv', index = False) # Saving pandas DataFrame as CSV |
my_df.to_csv('my_df.csv', index = False) # Saving pandas DataFrame as CSV
Example: Add New pandas DataFrame to Existing CSV File Vertically
my_df_new = pd.DataFrame({'A':range(10, 13), # Construct another DataFrame 'B':['foo', 'bar', 'foo'], 'C':range(100, 103)}) print(my_df_new) # A B C # 0 10 foo 100 # 1 11 bar 101 # 2 12 foo 102 |
my_df_new = pd.DataFrame({'A':range(10, 13), # Construct another DataFrame 'B':['foo', 'bar', 'foo'], 'C':range(100, 103)}) print(my_df_new) # A B C # 0 10 foo 100 # 1 11 bar 101 # 2 12 foo 102
my_df_new.to_csv('my_df.csv', # Append data at the bottom mode = 'a', header = False, index = False) |
my_df_new.to_csv('my_df.csv', # Append data at the bottom mode = 'a', header = False, index = False)
Further Resources & Related Articles
In addition, you may want to have a look at the related tutorials on this website: