Appen Column to Existing CSV File in Python (Example Code)

In this tutorial, I’ll demonstrate how to add a new column to a CSV file in the Python programming language.

Setting up the Example

import pandas as pd                         # Load 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.to_csv('my_df.csv', index = False)    # Saving pandas DataFrame as CSV

Example: Appending a New Column to a pandas DataFrame in a CSV File

col_D = ['x', 'x', 'y', 'y', 'x']           # Create new variable
print(col_D)
# ['x', 'x', 'y', 'y', 'x']
my_df_add = pd.read_csv('my_df.csv')        # Importing CSV file
my_df_add['D'] = col_D                      # Adding list to DataFrame
my_df_add.to_csv('my_df_add.csv')           # Saving updated DataFrame

Related Tutorials & Further Resources

Furthermore, you might want to read the related articles on this website. Some articles can be found below:

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top