The Wayback Machine - https://web.archive.org/web/20240624062040/https://www.geeksforgeeks.org/add-a-column-to-existing-csv-file-in-python/
Open In App

Add a Column to Existing CSV File in Python

Last Updated : 01 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Working with CSV files is a common task in data manipulation and analysis, and Python provides versatile tools to streamline this process. Here, we have an existing CSV file and our task is to add a new column to the existing CSV file in Python. In this article, we will see how we can add a column to a CSV file in Python.

Add a New Column to Existing CSV File in Python

Below, are examples of how to Add a New Column to an Existing CSV File in Python. Let’s consider an example of an existing CSV file with some sample data. Suppose your existing CSV file, named mon.csv, looks like this:

mon.csv

ex1

mon.csv

Example 1: Add New Column to Existing CSV Using Pandas

Pandas is a powerful data manipulation library in Python that makes working with tabular data seamless. Here’s how you can use Pandas to add a new column to an existing CSV file: In this example, below Python code utilizes the Pandas library to add a new ‘City‘ column with predefined values to an existing CSV file (‘mon.csv’). It reads the CSV into a DataFrame, appends the new column, and writes the updated DataFrame back to the same CSV file.

Python3




import pandas as pd
 
# Step 1: Read the CSV file into a DataFrame
csv_file_path = 'mon.csv'
df = pd.read_csv(csv_file_path)
 
# Step 2: Define the values for the new "City" column
new_city_values = ['New York', 'Los Angeles', 'Chicago', 'San Francisco']
 
# Step 3: Add the new "City" column to the DataFrame
df['City'] = new_city_values
 
# Step 4: Write the DataFrame back to the CSV file
df.to_csv(csv_file_path, index=False)


Output:

ex1-ans

updated

Example 2: Add New Column to Existing CSV Using CSV Module

The built-in csv module in Python also allows us to work with CSV files. Here’s how you can add a new column using the csv module: In this example, below code reads the content of an existing CSV file named ‘mon.csv‘ into a list of lists using the CSV module. It then adds a new column header ‘City’ to the first row and appends corresponding values to each subsequent row from the ‘new_city_values‘ list

Python3




import csv
 
# Step 1: Read the existing CSV file and store its content
csv_file_path = 'mon.csv'
with open(csv_file_path, 'r') as file:
    reader = csv.reader(file)
    data = list(reader)
 
# Step 2: Define the values for the new "City" column
new_city_values = ['New York', 'Los Angeles', 'Chicago', 'San Francisco']
 
# Step 3: Add the new "City" column header to the first row of the data
data[0].append('City')
 
# Step 4: Add the new "City" column values to the remaining rows of the data
for i in range(1, len(data)):
    data[i].append(new_city_values[i - 1])
 
# Step 5: Write the updated data back to the CSV file
with open(csv_file_path, 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)


Output:

ex1-ans

updated



Similar Reads

How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
How to append a new row to an existing csv file?
For writing a CSV file, the CSV module provides two different classes writer and Dictwriter. Here we will discuss 2 ways to perform this task effectively. The First will be 'append a list as a new row to the existing CSV file' and second way is 'Append a dictionary as a new row to the existing CSV file.' First, let's have a look at our existing CSV
3 min read
How to Append Pandas DataFrame to Existing CSV File?
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.t
3 min read
Replacing column value of a CSV file in Python
Let us see how we can replace the column value of a CSV file in Python. CSV file is nothing but a comma-delimited file. Method 1: Using Native Python way Using replace() method, we can replace easily a text into another text. In the below code, let us have an input CSV file as "csvfile.csv" and be opened in "read" mode. The join() method takes all
2 min read
How to Sort data by Column in a CSV File in Python ?
In this article, we will discuss how to sort CSV by column(s) using Python. Method 1: Using sort_values() We can take the header name as per our requirement, the axis can be either 0 or 1, where 0 means 'rows' and '1' means 'column'. Ascending can be either True/False and if True, it gets arranged in ascending order, if False, it gets arranged in d
3 min read
Read CSV File without Unnamed Index Column in Python
Whenever the user creates the data frame in Pandas, the Unnamed index column is by default added to the data frame. The article aims to demonstrate how to read CSV File without Unnamed Index Column using index_col=0 while reading CSV. Read CSV File without Unnamed Index Column Using index_col=0 while reading CSVThe way of explicitly specifying whic
2 min read
How to create a duplicate file of an existing file using Python?
In this article, we will discuss how to create a duplicate of the existing file in Python. Below are the source and destination folders, before creating the duplicate file in the destination folder. After a duplicate file has been created in the destination folder, it looks like the image below. For automating of copying and removal of files in Pyt
5 min read
How To Calculate Average For Every Column In A Csv File
We are given a CSV file and our task is to find the average of each column in Python using different approaches. In this article, we will see how we can calculate the average for every column in a CSV file. Example: Input: data.csv Age,Salary 30,50000 25,60000 28,55000 Output: Average Age: 27.67, Average Salary: 55000.00Calculate the Average For Ev
3 min read
Python program to read CSV without CSV module
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the nam
3 min read
Copying Csv Data Into Csv Files Using Python
CSV files, the stalwarts of information exchange, can be effortlessly harnessed to extract specific data or merge insights from multiple files. In this article, we unveil five robust approaches, transforming you into a virtuoso of CSV data migration in Python. Empower your data-wrangling endeavors, mastering the art of copying and organizing inform
4 min read
Practice Tags :
three90RightbarBannerImg