The Wayback Machine - https://web.archive.org/web/20240918165208/https://www.geeksforgeeks.org/how-to-delete-only-one-row-in-csv-with-python/
Open In App

How to delete only one row in CSV with Python?

Last Updated : 24 Jan, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisites: pandas

One can open and edit CSV files in Python via Pandas library. While editing the file one might want to remove the entire row in the file. Following are some different approaches to do the same:

Data set in use: iris.csv dataset 

Method 1: Using slicing

This method is only good for removing the first or the last row from the dataset. And the following two lines of code which although means same represent the use of the .iloc[]  method in pandas.

Syntax:

df.iloc[<row_number>, <column_number>]

or

df.iloc[<row_number>]

Approach: To remove first row

  • Import the library
  • Load the dataset in python
  • To remove the first-row using slicing. Since the index column by default is numeric, hence the index label will also be integers.

(0 indexes will be removed as in python indexing starts from 0):

Program:

Python3




import pandas as pd
  
df = pd.read_csv(url)
  
df = df.iloc[1:]
  
print(df)


Output

removing first row

Approach: To remove the last row 

  • import the library
  • load the dataset in python
  • to remove the last-row using slicing. As the index column by default is numeric, hence the index label will also be integers.

(here -1 represents the last row of the data)

Program:

Python3




import pandas as pd
  
df = pd.read_csv(url)
  
df = df.iloc[:-1]
  
print(df)


Output

removing last row

Method 2: Using drop() method

Removing using Label means the name of the row is specified in the code whereas using indexing means the index(position/ row number starting from 0) of the row is specified in the code.

Data set in use:

subset – top 5 items

Approach: Using row label

  • Import pandas library
  • Load dataset
  • Select required data
  • With the use of row label (here 5.1) dropping the row corresponding to the same label. Label can be of any data type (string or integer or float etc).

Program:

Python3




import pandas as pd
  
df = pd.read_csv(url)
  
# 2.
df_s = df[:5]
  
# 3.
df_s.set_index('sepal_length', inplace=True)
  
# 4.1.
df_s = df_s.drop(5.1)
  
print(df_s)


Output

using row label 

Approach: Using row index

  • Import pandas library
  • Load dataset
  • Select required data
  • With the use of row index one needs to pass the index of the row to be removed.

df.index[ ] takes index numbers as a parameter starting from 1 and onwards whereas in python indexing starts from 0.

Program:

Python3




import pandas as pd
  
df = pd.read_csv(url)
  
df_s = df[:5]
  
df_s.set_index('sepal_length', inplace=True)
  
df_s = df_s.drop(df_s.index[1])
#df_s.drop(df_s.index[1],inplace = True)
  
print(df_s)


Output

using row index

Method 3: Removing using Conditions 

Dataset in use:

subset – top 5 items

Approach 1:

  • Import module
  • Load data
  • Select required data
  • Find the row that specifies the specified condition
  • Use drop() method and pass the index of the fetched row as a parameter in the drop method.

Program:

Python3




import pandas as pd
  
df = pd.read_csv(url)
  
  
df_s1 = df[:5]
  
  
df_s1 = df_s1.drop(df_s1[(df_s1.sepal_length == 4.7) &
                         (df_s1.petal_length == 1.3)].index)
  
print(df_s1)


Output

first method – conditional removal

                                  

Approach 2:

  • Import module
  • Load data
  • Select required data
  • Find the row that specifies the specified condition using query() method
  • Use drop() method and pass the index of the fetched row as a parameter in the drop method.

Program:

Python3




import pandas as pd
  
df = pd.read_csv(url)
  
df_s1 = df[:5]
  
df_s1 = df_s1.drop(df_s1.query('sepal_length==5.0').index)
  
print(df_s1)


Output:

second method – conditional removal

 



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
Writing data from a Python List to CSV row-wise
Comma Separated Values (CSV) files a type of a plain text document in which tabular information is structured using a particular format. A CSV file is a bounded text format which uses a comma to separate values. The most common method to write data from a list to CSV file is the writerow() method of writer and DictWriter class. Example 1: Creating
2 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. Approach : Import module.Check the path of the file.
2 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 separated with a comma(separator), also known as a
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 Delete a Specific Row from SQLite Table using Python ?
In this article, we will discuss how to delete of a specific row from the SQLite table using Python. In order to delete a particular row from a table in SQL, we use the DELETE query, The DELETE Statement in SQL is used to delete existing records from a table. We can delete a single record or multiple records depending on the condition we specify in
3 min read
How to Delete Only Empty Folders in Python
In this article, we are going to see how to delete only empty folders in Python. Before deleting the folder, here is an image showing the files inside the main directory. As the above image is showing that the folder has 2 empty sub-folders and 1 non-empty folder. So, after running the code these 2 folders must get deleted. By using os module With
1 min read
How to Apply a Custom Function in Polars that Does the Processing Row by Row?
Polars is a fast DataFrame library in Rust and Python, designed to handle large datasets efficiently. It provides a powerful API for data manipulation, similar to pandas, but with performance optimizations that can significantly speed up your data processing tasks. One common task in data processing is applying custom functions to manipulate data r
5 min read
How to add one row in an existing Pandas DataFrame?
Adding rows to a Pandas DataFrame is a common task in data manipulation. Here are the primary methods to add rows to a DataFrame, along with their syntax and examples in Pandas. Add Row to Pandas Dataframe # Append the new row to the DataFramedf = df.append(new_row, ignore_index=True)print(df)Table of Content Add Row to Dataframe using df.locPandas
4 min read
How to delete one or more rows in excel using Openpyxl?
Openpyxl is a Python library to manipulate xlsx/xlsm/xltx/xltm files. With Openpyxl you can create a new Excel file or a sheet and can also be used on an existing Excel file or sheet. Installation This module does not come built-in with Python. To install this type the below command in the terminal. pip3 install openpyxl In this article, we will di
5 min read
How to Add padding to a tkinter widget only on one side ?
In this article, we will discuss the procedure of adding padding to a Tkinter widget only on one side. Here, we create a widget and use widget.grid() method in tkinter to padding the content of the widget. For example, let's create a label and use label.grid() method. Below the syntax is given: label1 = Widget_Name(app, text="text_to_be_written_in_
2 min read
Check if a substring exists having only 2 distinct characters with frequency of one as twice the others
Given a string str[] of N lower case English alphabets, the task is to check if there exists a substring of the given string such that the substring is composed of only two characters and the frequency of 1st character = 2 * frequency of 2nd character. Example: Input: str[] = "aaaabbc"Output: YesExplanation: The substring str[0... 5] = "aaaabb" of
6 min read
How To Select Only One Column Using SQLAlchemy?
In this article, we are going to see how to select only one column using SQLAlchemy in Python. SQLAlchemy is a large SQL toolkit with lots of different components. The two largest components are SQLAlchemy Core and SQLAlchemy ORM. The major difference between them is SQLAlchemy Core is a schema-centric model that means everything is treated as a pa
3 min read
How to resolve a UnicodeDecodeError for a CSV file in Python?
Several errors can arise when an attempt to decode a byte string from a certain coding scheme is made. The reason is the inability of some encoding schemes to represent all code points. One of the most common errors during these conversions is UnicodeDecode Error which occurs when decoding a byte string by an incorrect coding scheme. This article w
5 min read
Python - Read CSV Column into List without header
Prerequisites: Reading and Writing data in CSV CSV files are parsed in python with the help of csv library. The csv library contains objects that are used to read, write and process data from and to CSV files. Sometimes, while working with large amounts of data, we want to omit a few rows or columns, so that minimum memory gets utilized. Let's see
2 min read
Update column value of CSV in Python
Prerequisites: Pandas In this article, we will discuss ways in which the value(s) of a column can be updated. The best and the optimal way to update any column value of a CSV is to use the Pandas Library and the DataFrame functions. Link for the CSV file in use - Click here Method 1 Approach Import moduleOpen CSV file and read its dataFind column t
3 min read
Scrape and Save Table Data in CSV file using Selenium in Python
Selenium WebDriver is an open-source API that allows you to interact with a browser in the same way a real user would and its scripts are written in various languages i.e. Python, Java, C#, etc. Here we will be working with python to scrape data from tables on the web and store it as a CSV file. As Google Chrome is the most popular browser, to make
3 min read
Convert CSV to Excel using Pandas in Python
Pandas can read, filter, and re-arrange small and large datasets and output them in a range of formats including Excel. In this article, we will be dealing with the conversion of .csv file into excel (.xlsx). Pandas provide the ExcelWriter class for writing data frame objects to excel sheets. Syntax: final = pd.ExcelWriter('GFG.xlsx') Example:Sampl
1 min read
Convert JSON to CSV in Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
3 min read
Saving Text, JSON, and CSV to a File in Python
Python allows users to handle files (read, write, save and delete files and many more). Because of Python, it is very easy for us to save multiple file formats. Python has in-built functions to save multiple file formats. Opening a text file in Python Opening a file refers to getting the file ready either for reading or for writing. This can be don
5 min read
Convert CSV to HTML Table in Python
CSV file is a Comma Separated Value file that uses a comma to separate values. It is basically used for exchanging data between different applications. In this, individual rows are separated by a newline. Fields of data in each row are delimited with a comma.Example : Name, Salary, Age, No.of years employed Akriti, 90000, 20, 1 Shreya, 100000, 21,
2 min read
Convert HTML table into CSV file in python
CSV file is a Comma Separated Value file that uses a comma to separate values. CSV file is a useful thing in today's world when we are talking about machine learning, data handling, and data visualization. In this article, we will discuss how to convert an HTML table into a CSV file. Converting HTML Table into CSV file in Python Example: Suppose HT
2 min read
Python - Save List to CSV
A CSV (Comma Separated Values) is a simple file format, used to store data in a tabular format. 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 form
3 min read
Reading and Writing CSV Files in Python
CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. It is one of the most common methods for exchanging data between applications and popular data format used in Data Science. It is supported by a wide range of applications. A CSV file stores tabular data in which each data field is separa
4 min read
How to save a Python Dictionary to a CSV File?
Prerequisites: Working with csv files in Python CSV (comma-separated values) files are one of the easiest ways to transfer data in form of string especially to any spreadsheet program like Microsoft Excel or Google spreadsheet. In this article, we will see how to save a PYthon dictionary to a CSV file. Follow the below steps for the same. Import cs
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 having data about Customer Serial Number, Customer
3 min read
How to Convert an image to NumPy array and saveit to CSV file using Python?
Let's see how to Convert an image to NumPy array and then save that array into CSV file in Python? First, we will learn about how to convert an image to a numpy ndarray. There are many methods to convert an image to ndarray, few of them are: Method 1: Using PIL and NumPy library. We will use PIL.Image.open() and numpy.asarray(). Example: C/C++ Code
4 min read
Convert Text File to CSV using Python Pandas
Let's see how to Convert Text File to CSV using Python Pandas. Python will read data from a text file and will create a dataframe with rows equal to number of lines present in the text file and columns equal to the number of fields present in a single line. See below example for better understanding. Dataframe created from upper text file will look
2 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
Convert multiple JSON files to CSV Python
In this article, we will learn how to convert multiple JSON files to CSV file in Python. Before that just recall some terms : JSON File: A JSON file may be a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which may be a standard data interchange format. It is primarily used for transmitting data bet
8 min read
Article Tags :
Practice Tags :