In this article we will discuss how to delete rows based in DataFrame by checking multiple conditions on column values.

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).

Let’s use this do delete multiple rows by conditions.

Let’s create a dataframe object from dictionary

Delete rows based on condition on a column

Contents of dataframe object dfObj will be,

Original DataFrame pointed by dfObj

Let’s delete all rows for which column ‘Age’ has value 30 i.e.

Contents of updated dataframe object dfObj will be,

DataFrame rows with value 30 in Column Age are deleted

What just happened here ? Let’s understand,

It will give Series object with True and False. True for entries which has value 30 and False for others i.e.

Let’s create a new DataFrame object with this series and existing DataFrame object dfObj i.e.

It will give a new dataframe object that has only that row for which column ‘Age’ has value 30 i.e.

   Name Age City   Country
b Riti    30    Delhi  India

Now, this dataframe contains the rows which we want to delete from original dataframe. So, let’s get the index names from this dataframe object i.e.

It will give an Index object containing index labels for which column ‘Age’ has value 30 i.e.

Now pass this to dataframe.drop() to delete these rows i.e.

It will delete the all rows for which column ‘Age’ has value 30.

Delete rows based on multiple conditions on a column

Suppose Contents of dataframe object dfObj is,

Original DataFrame pointed by dfObj

Let’s delete all rows for which column ‘Age’ has value between 30 to 40 i.e.

Contents of modified dataframe object dfObj will be,

Rows with column ‘Age’ value 30 to 40 deleted

basically we need to use & between multiple conditions.

Delete rows based on multiple conditions on different columns

Suppose Contents of dataframe object dfObj is,

Original DataFrame pointed by dfObj

Let’s delete all rows for which column ‘Age’ has value greater than 30 and country is ‘India’

Contents of modified dataframe object dfObj will be,

Rows deleted whose Age > 30 & country is India

We need to use & between multiple conditions.

Complete Example is as follows,

Output:

 

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