Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data preprocessing
  • Data Manipulation
  • Data Analysis using Pandas
  • EDA
  • Pandas Exercise
  • Pandas AI
  • Numpy
  • Matplotlib
  • Plotly
  • Data Analysis
  • Machine Learning
  • Data science
Open In App
Next Article:
Delete a CSV Column in Python
Next article icon

Replacing column value of a CSV file in Python

Last Updated : 02 Sep, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

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 lines of a CSV file in an iterable and joins them into one string. Then, we can use replace() method on the entire string and can perform single/multiple replacements. In the entire string, the given text is searched and replaced with the specified text.

Example: 

The input file will be:

Python3

# reading the CSV file
text = open("csvfile.csv", "r")
  
#join() method combines all contents of 
# csvfile.csv and formed as a string
text = ''.join([i for i in text]) 
  
# search and replace the contents
text = text.replace("EmployeeName", "EmpName") 
text = text.replace("EmployeeNumber", "EmpNumber") 
text = text.replace("EmployeeDepartment", "EmpDepartment") 
text = text.replace("lined", "linked") 
  
# output.csv is the output file opened in write mode
x = open("output.csv","w")
  
# all the replaced text is written in the output.csv file
x.writelines(text)
x.close()
                      
                       

Output:

Method 2: Using Pandas DataFrame

We can read the CSV file as a DataFrame and then apply the replace() method.

Python3

# importing the module
import pandas as pd 
    
# making data frame from the csv file 
dataframe = pd.read_csv("csvfile1.csv") 
    
# using the replace() method
dataframe.replace(to_replace ="Fashion", 
                 value = "Fashion industry", 
                  inplace = True)
dataframe.replace(to_replace ="Food", 
                 value = "Food Industry", 
                  inplace = True)
dataframe.replace(to_replace ="IT", 
                 value = "IT Industry", 
                  inplace = True)
  
# writing  the dataframe to another csv file
dataframe.to_csv('outputfile.csv', 
                 index = False)
                      
                       

Output:



Next Article
Delete a CSV Column in Python
author
priyarajtt
Improve
Article Tags :
  • Python
  • python-csv
  • Python-pandas
Practice Tags :
  • python

Similar Reads

  • Copy And Replace Files in Python
    In Python, copying and replacing files is a common task facilitated by modules like `shutil` and `os`. This process involves copying a source file to a destination location while potentially replacing any existing file with the same name. Leveraging functions like `shutil.copy2` and `os.remove`, thi
    2 min read
  • Reading and Writing CSV Files in Python
    CSV (Comma Separated Values) format is one of the most widely used formats for storing and exchanging structured data between different applications, including databases and spreadsheets. CSV files store tabular data, where each data field is separated by a delimiter, typically a comma. Python provi
    4 min read
  • Reading CSV files in Python
    A CSV (Comma Separated Values) file is a form of plain text document that uses a particular format to organize tabular information. CSV file format is a bounded text document that uses a comma to distinguish the values. Every row in the document is a data log. Each log is composed of one or more fie
    5 min read
  • Delete a CSV Column in Python
    The comma-separated values ​​(CSV) file is a delimited text file that uses commas for individual values. Each line of the file is a data record in CSV. This format used for tabular data, rows, and columns, exactly like a spreadsheet. The CSV file stores data in rows and the values ​​in each row are
    3 min read
  • How to Replace Values in a List in Python?
    Replacing values in a list in Python can be done by accessing specific indexes and using loops. In this article, we are going to see how to replace the value in a List using Python. We can replace values in the list in several ways. The simplest way to replace values in a list in Python is by using
    2 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 whil
    2 min read
  • Reading specific columns of a CSV file using Pandas
    When working with large datasets stored in CSV (Comma-Separated Values) files, it’s often unnecessary to load the entire dataset into memory. Instead, you can selectively read specific columns using Pandas in Python. Read Specific Columns From CSV FileLet us see how to read specific columns of a CSV
    3 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 i
    3 min read
  • Replace Commas with New Lines in a Text File Using Python
    Replacing a comma with a new line in a text file consists of traversing through the file's content and substituting each comma with a newline character. In this article, we will explore three different approaches to replacing a comma with a new line in a text file. Replace Comma With a New Line in a
    2 min read
  • How to Change Values in a String in Python
    The task of changing values in a string in Python involves modifying specific parts of the string based on certain conditions. Since strings in Python are immutable, any modification requires creating a new string with the desired changes. For example, if we have a string like "Hello, World!", we mi
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences