How to delete only one row in CSV with Python?
Last Updated :
24 Jan, 2021
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
url = "https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv"
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
url = "https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv"
df = pd.read_csv(url)
df = df.iloc[:-1]
print(df)
Output
removing last rowMethod 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
url = "https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv"
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
url = "https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv"
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 indexMethod 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
url = "https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv"
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
url = "https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv"
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 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
How to read numbers in CSV files in Python? Prerequisites: Reading and Writing data in CSV, Creating CSV files CSV is a Comma-Separated Values file, which allows plain-text data to be saved in a tabular format. These files are stored in our system with a .csv extension. CSV files differ from other spreadsheet file types (like Microsoft Excel
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.
5 min read
How to write to CSV in R without index ? We know that when we write some data from DataFrame to CSV file then a column is automatically created for indexing. We can remove it by some modifications. So, in this article, we are going to see how to write CSV in R without index. To write to csv file write.csv() is used. Syntax: write.csv(data,
2 min read
How to Read CSV Files with NumPy? Reading CSV files is a common task when working with data in Python. In this article we will see how to read CSV files using Numpy's loadtxt() and genfromtxt() methods.1. Using NumPy loadtxt() methodThe loadtext() method is faster and simpler for reading CSV files. It is best when the file has consi
2 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 o
2 min read
How To Delete Cell In Jupiter Notebook Jupyter Notebook is a powerful tool for developers. Jupyter is an open-source web application that contains both code and text elements such as figures, questions, pictures, etc. Jupiter's main meaning is Julia, Python, and Ruby. Jupyter Notebook is a web-based computational environment for creating
3 min read
How to add timestamp to CSV file in Python Prerequisite: Datetime module In this example, we will learn How to add timestamp to CSV files in Python. We can easily add timestamp to CSV files with the help of datetime module of python. Let's the stepwise implementation for adding timestamp to CSV files in Python. Creating CSV and adding timest
5 min read
How to Remove Item from a List in Python Lists in Python have various built-in methods to remove items such as remove, pop, del and clear methods. Removing elements from a list can be done in various ways depending on whether we want to remove based on the value of the element or index.The simplest way to remove an element from a list by i
3 min read