How to Delete a Row From a Pandas DataFrame in Python

There are multiple ways to delete a row from a Pandas DataFrame in Python. I have an another article How to Create a Pandas DataFrame in Python, where you will learn how to create a Pandas DataFrame in Python. For this tutorial, I will use a sample DataFrame as below:

       id      name  math_score
0  202301    Minhaj          92
1  202302   Ridhwan          86
2  202303   Tanveer          76
3  202304  Sharodia          89
4  202305      Alve          99
5  202306   Intisar          99

One way is to use the drop() method, which allows you to specify the index or indices of the rows you want to drop. For example, if you want to drop the first row of a DataFrame called “df”, you can use the following code:

df = df.drop(0)

You could also use the index label to drop the row:

df = df.drop(df.index[0])

Another option is to use the iloc property to select the row by its position and then use the drop() method on the resulting DataFrame. For example, if you want to drop the first row of a DataFrame called “df”, you can use the following code:

df = df.drop(df.index[0])

You could also use the query() function along with the drop() function to drop the rows based on a condition:

#sample structure
df = df.query('column_name != "value"').drop()
#actual code regarding the above data table
df = df.query('math_score != 99').drop()

If you’re working with a large DataFrame and you only want to drop a specific subset of rows, you can use boolean indexing to select the rows you want to keep, and then assign the resulting DataFrame back to the original DataFrame. Here is an example:

df = df[df.column_name != 'value']

In this tutorial, I tried to brief how to delete a row from Pandas DataFrame in Python. Hope you have enjoyed the tutorial. If you want to get updated, like my facebook page https://www.facebook.com/LearningBigDataAnalytics and stay connected.

Add a Comment