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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Add a Column to Existing CSV File in Python
Next article icon

Delete a CSV Column in Python

Last Updated : 23 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 separated with a comma(separator), also known as a delimiter.

There are 2 ways to remove a column entirely from a CSV in python. Let us now focus on the techniques :

  1. With pandas library — drop() or pop()
  2. Without pandas library

Here, a simple CSV file is used i.e;input.csv

iddaymonthyearitem_quantityName
1123202012Oliver
2133202045Henry
314320208Benjamin
4153202023John
5163202031Camili
6173202040Rheana
7183202055Joseph
8193202013Raj
9203202029Elias
10213202019Emily

Method 1: Using pandas library

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas consist of a drop function that is used in removing rows or columns from the CSV files. Pandas Pop() method is common in most of the data structures but the pop() method is a little different from the rest. In a stack, pop doesn’t require any parameters, it pops the last element every time. But the pandas pop method can take input of a column from a data frame and pop that directly.

Example 1: Using drop()

data.drop( labels=None, axis=0, index=None, columns=None, level=None, inplace=False,errors='raise')

  1. Import Pandas
  2. Read CSV File
  3. Use drop() function for removing or deleting rows or columns from the CSV files
  4. Print Data

Python3

# import pandas with shortcut 'pd'
import pandas as pd  
  
# read_csv function which is used to read the required CSV file
data = pd.read_csv('input.csv')
  
# display 
print("Original 'input.csv' CSV Data: \n")
print(data)
  
# drop function which is used in removing or deleting rows or columns from the CSV files
data.drop('year', inplace=True, axis=1)
  
# display 
print("\nCSV Data after deleting the column 'year':\n")
print(data)
                      
                       

Output:

Example 2: Using pop()

We can use the panda pop () method to remove columns from CSV by naming the column as an argument.

[Tex]data.pop('column-name')[/Tex]

  1. Import Pandas
  2. Read CSV File
  3. Use pop() function for removing or deleting rows or columns from the CSV files
  4. Print Data

Python3

# import pandas with shortcut 'pd'
import pandas as pd
  
# read_csv function which is used to read the required CSV file
data = pd.read_csv('input.csv')
  
# display
print("Original 'input.csv' CSV Data: \n")
print(data)
  
# pop function which is used in removing or deleting columns from the CSV files
data.pop('year')
  
# display
print("\nCSV Data after deleting the column 'year':\n")
print(data)
                      
                       

Output:

Method 2: Using CSV library

Example 3: Using CSV read and write

  1. Open Input CSV file as source
  2. Read Source CSV File
  3. Open Output CSV File as a result
  4. Put source CSV data in result CSV using indexes

Python3

# import csv
import csv
  
# open input CSV file as source
# open output CSV file as result
with open("input.csv", "r") as source:
    reader = csv.reader(source)
      
    with open("output.csv", "w") as result:
        writer = csv.writer(result)
        for r in reader:
            
            # Use CSV Index to remove a column from CSV
            #r[3] = r['year']
            writer.writerow((r[0], r[1], r[2], r[4], r[5]))
                      
                       

Output:



Next Article
Add a Column to Existing CSV File in Python

K

kg_code
Improve
Article Tags :
  • Python
  • python-csv
Practice Tags :
  • python

Similar Reads

  • Python - Numpy Array Column Deletion
    Given a numpy array, write a programme to delete columns from numpy array. Examples - Input: [['akshat', 'nikhil'], ['manjeeet', 'akash']] Output: [['akshat']['manjeeet']] Input: [[1, 0, 0, 1, 0], [0, 1, 2, 1, 1]] Output: [[1 0 1 0][0 2 1 1]] Given below are various methods to delete columns from nu
    2 min read
  • Add a Column to Existing CSV File in Python
    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 t
    3 min read
  • How to delete a CSV file in Python?
    In this article, we are going to delete a CSV file in Python. CSV (Comma-separated values file) is the most commonly used file format to handle tabular data. The data values are separated by, (comma). The first line gives the names of the columns and after the next line the values of each column. Ap
    2 min read
  • Convert Excel to CSV in Python
    In this article, we will be dealing with the conversion of Excel (.xlsx) file into .csv. There are two formats mostly used in Excel : (*.xlsx) : Excel Microsoft Office Open XML Format Spreadsheet file.(*.xls) : Excel Spreadsheet (Excel 97-2003 workbook). Let's Consider a dataset of a shopping store
    3 min read
  • Python - Read CSV Columns Into List
    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 name for this file format. In this article, we will read data from a
    3 min read
  • How to Delete Blank Columns in Excel
    Empty columns in your Excel spreadsheet can make it look messy and also look unprofessional. Now, whether you are doing a budget analysis, sorting data, or making a report, removing blank columns is a way to make your report professional and cleaner. Now, if you are new to MS Excel and want to know
    5 min read
  • How to Delete Column in SQL
    In SQL, deleting a column from an existing table is a straightforward process, but it's important to understand the implications and the correct syntax involved. While there is no direct DELETE COLUMN command in SQL, we can achieve this by using the ALTER TABLE command combined with DROP COLUMN. In
    5 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 o
    2 min read
  • Get column names from CSV using Python
    CSV (Comma Separated Values) files store tabular data as plain text, with values separated by commas. They are widely used in data analysis, machine learning and statistical modeling. In Python, you can work with CSV files using built-in libraries like csv or higher-level libraries like pandas. In t
    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 i
    3 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