In this article we will discuss how to delete single or multiple rows from a DataFrame object.

DataFrame provides a member function drop() i.e.

It accepts a single or list of label names and deletes the corresponding rows or columns (based on value of axis parameter i.e. 0 for rows or 1 for columns). As default value for axis is 0, so for dropping rows we need not to pass axis.

Also, by default drop() doesn’t modify the existing DataFrame, instead it returns a new dataframe. If we want to update the existing DataFrame in place then we need to pass another attribute i.e.

Let’s understand by examples,

Let’s create a DataFrame object containing student details i.e.

Delete a single Row in DataFrame by Row Index Label

Contents of DataFrame object dfObj is,

Original DataFrame pointed by dfObj

Let’s delete the row with index ‘d’ from DataFrame dfObj i.e.

Contents of returned dataframe object modDfObj will be,

Row with index label ‘b’ is not in new DataFrame Object. As default value of inPlace is false, so contents of dfObj will not be modified.

Delete Multiple Rows in DataFrame by Index Labels

Contents of DataFrame object dfObj is,

Original DataFrame pointed by dfObj

Let’s delete the rows with index ‘b’ , ‘c’ & ‘e’ from above dataframe i.e.

Contents of returned dataframe object modDfObj will be,

DataFrame without rows a & b

As default value of inPlace is false, so contents of dfObj will not be modified.

Delete a Multiple Rows by Index Position in DataFrame

Contents of dataframe object dfObj is,

Original DataFrame pointed by dfObj

As df.drop() function accepts only list of index label names only, so to delete the rows by position we need to create a list of index names from positions and then pass it to drop().
Suppose we want to delete the first two rows i.e. rows at index position 0 & 1 from the above dataframe object. Let’s see how to do that,

Contents of returned dataframe object modDfObj will be,

DataFrame without rows a & b

As default value of inPlace is false, so contents of dfObj will not be modified.

Delete rows from dataFrame in Place

In all the above examples drop() function was not updating the existing dataframe object, it was returning a new dataframe object.
So, to update the existing dataframe object we need to pass the parameter inPlace with value True. Let’s understand by example,

Contents of original dataframe object dfObj is,

Original DataFrame pointed by dfObj

Drop a column ‘a’ & ‘b’ from dfObj in place i.e.

Contents of updated dfObj is,

DataFrame without rows a & b

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.