The Wayback Machine - https://web.archive.org/web/20240717145210/https://www.geeksforgeeks.org/drop-rows-from-the-dataframe-based-on-certain-condition-applied-on-a-column/
Open In App

Drop rows from the dataframe based on certain condition applied on a column

Last Updated : 11 Jul, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

In this post, we are going to discuss several approaches on how to drop rows from the dataframe based on certain conditions applied to a column. Retain all those rows for which the applied condition on the given column evaluates to True. 

We have already discussed earlier how to drop rows or columns based on their labels. However, in this post, we are going to discuss several approaches on how to drop rows from the data frame based on certain conditions applied to a column. Retain all those rows for which the applied condition on the given column evaluates to True.

Python Pandas Conditionally Delete Rows

Below are the ways by which we can drop rows from the dataframe based on certain conditions applied on a column, but before that we will create a datframe for reference:

  • Create a datframe for reference:
  • Using drop()
  • Using query()
  • Using loc[]
  • Using isin()
  • Using eval()

To download the CSV (“nba.csv” dataset) used in the code, click here. 

Reference: How to drop rows or columns based on their labels

Creating a Dataframe to drop Rows

 In this Dataframe, currently, we have 458 rows and 9 columns.

Python
# importing pandas as pd
import pandas as pd

# Read the csv file and construct the 
# dataframe
df = pd.read_csv('nba.csv')

# Visualize the dataframe
print(df.head(15))

Output:

Delete Rows Based on Multiple Conditions on a Column

We will use vectorization to filter out such rows from the dataset which satisfy the applied condition. Let’s use the vectorization operation to filter out all those rows which satisfy the given condition.

Python
# Filter rows where the player's age is 25 or older
filtered_df = df[df['Age'] >= 25]

# Display the first 15 rows of the filtered DataFrame
print(filtered_df.head(15))

Output:

As we can see in the output, the returned Dataframe only contains those players whose age is greater than or equal to 25 years. 

Delete Rows Based on Multiple Conditions on a Column Using drop()

Example 1: As we can see in the output, the returned Dataframe only contains those players whose age is not between 20 to 25 age using df.drop(). 

Python
# Delete all rows with column 'Age' has value 20 to 25 
indexAge = df[ (df['Age'] >= 20) & (df['Age'] <= 25) ].index
df.drop(indexAge , inplace=True)
df.head(15)

Output

Example 2: Here, we drop all the rows whose names and Positions are associated with ‘John Holland‘ or ‘SG’ using df.drop().

Python
# Delete rows where the 'Name' is 'John Holland' or the 'Position' is 'SG'
indexAge = df[(df['Name'] == 'John Holland') | (df['Position'] == 'SG')].index
df.drop(indexAge, inplace=True)
df.head(15)

Output

Delete Rows Based on Multiple Conditions on a Column Using query()

In this example, we are using query() function to delete rows based on multiple conditions on a column. Below code creates a DataFrame and filters it to keep only individuals aged 30 or younger using the `query` function. The resulting DataFrame is printed.

Python
import pandas as pd

# Create a sample DataFrame
data = {'name': ['Alice', 'Bob', 'Charlie', 'Dave'],
        'age': [25, 30, 35, 40],
        'gender': ['F', 'M', 'M', 'M']}
df = pd.DataFrame(data)

# Use the query function to filter the DataFrame 
#for individuals aged 30 or younger
df_new = df.query('age <= 30')

# Print the resulting DataFrame
print(df_new)

Output

    name  age gender
0 Alice 25 F
1 Bob 30 M

Delete Rows Based on Multiple Conditions on a Column Using loc

In this example, we are using loc function to delete rows based on multiple conditions on a column. Below code generates a DataFrame and filters it to retain rows where the ‘age’ is 30 or less, displaying the modified DataFrame.

Python
import pandas as pd

# create a sample data frame
data = {'name': ['Alice', 'Bob', 'Charlie', 'Dave'],
        'age': [25, 30, 35, 40],
        'gender': ['F', 'M', 'M', 'M']}
df = pd.DataFrame(data)

# Use the loc method to filter the DataFrame
df_new = df.loc[df['age'] <= 30]

# Print the resulting DataFrame
print(df_new)

Output

It uses the isin() method to create a boolean mask based on the specified condition and then uses that mask to filter out the rows.

   name  age gender
0 Alice 25 F
1 Bob 30 M

Delete Rows Based on Multiple Conditions on a Column Using isin()

In this example , we are using isin() method to create a boolean mask based on the specified condition and then uses that mask to filter out the rows. Below code generates a DataFrame with ‘Name,’ ‘Age,’ and ‘Score,’ filters out rows where ‘Score’ is less than 80, and displays the modified DataFrame.

Python
import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
        'Age': [25, 30, 35, 40, 45],
        'Score': [85, 92, 78, 65, 89]}

df = pd.DataFrame(data)

# Define the condition
condition = (df['Score'] < 80)

# Delete rows based on the condition
df = df[~condition]

print("DataFrame after deleting rows based on condition:")
print(df)

Output :

DataFrame after deleting rows based on condition:
Name Age Score
0 Alice 25 85
1 Bob 30 92
4 Eva 45 89

Delete Rows Based on Multiple Conditions on a Column Using eval()

In this example , we are using the eval() method to evaluate a boolean condition and filter the DataFrame accordingly. The Below code creates a DataFrame, sets a condition where ‘Score’ < 80, and removes corresponding rows, displaying the updated DataFrame.

Python
import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
        'Age': [25, 30, 35, 40, 45],
        'Score': [85, 92, 78, 65, 89]}

df = pd.DataFrame(data)

# Delete rows based on a condition using eval()
df = df.eval('Score >= 80')

print("DataFrame after deleting rows based on condition:")
print(df)

Output :

DataFrame after deleting rows based on condition:
0 True
1 True
2 False
3 False
4 True
dtype: bool


How to drop rows in DataFrame by condition on column values?

To drop rows based on a specific condition, use the drop() method in conjunction with a condition that identifies the rows. You can also use boolean indexing to filter out the rows:

import pandas as pd

df = pd.DataFrame({
'A': [1, 2, 3, 4],
'B': [5, 6, 7, 8]
})

# Drop rows where column 'A' is less than 3
df = df[df['A'] >= 3]
print(df)

How to drop rows with missing values in a specific column in pandas?

To remove rows that contain missing values in a specific column, use the dropna() method specifying the subset parameter:

df = pd.DataFrame({
'A': [1, 2, None, 4],
'B': ['a', 'b', 'c', None]
})

# Drop rows where column 'A' has NaN
df.dropna(subset=['A'], inplace=True)
print(df)

How to drop multiple rows in pandas?

You can drop multiple rows by their index labels using the drop() method:

# Assuming you know the index labels of the rows to drop
df.drop([0, 2], inplace=True)
print(df)

How to drop unique rows in a DataFrame?

Dropping unique rows typically refers to removing duplicate rows, where you want to keep only unique records:

df = pd.DataFrame({
'A': [1, 2, 2, 4],
'B': ['a', 'b', 'b', 'd']
})

# Drop duplicate rows, keeping the first occurrence
df.drop_duplicates(inplace=True)
print(df)

How to drop rows from a specific column in Pandas?

If you intend to drop rows based on conditions in a specific column, it follows the pattern shown earlier using boolean indexing:

df = pd.DataFrame({
'A': [1, 2, 2, 4],
'B': ['a', 'b', 'b', 'd']
})

# Drop duplicate rows, keeping the first occurrence
df.drop_duplicates(inplace=True)
print(df)


Previous Article
Next Article

Similar Reads

Drop rows in PySpark DataFrame with condition
In this article, we are going to drop the rows in PySpark dataframe. We will be considering most common conditions like dropping rows with Null values, dropping duplicate rows, etc. All these conditions use different functions and we will discuss these in detail. We will cover the following topics: Drop rows with condition using where() and filter(
5 min read
Python PySpark - Drop columns based on column names or String condition
In this article, we will be looking at the step-wise approach to dropping columns based on column names or String conditions in PySpark. Stepwise ImplementationStep1: Create CSV Under this step, we are simply creating a CSV file with three rows and columns. CSV Used: Step 2: Import PySpark Library Under this step, we are importing the PySpark packa
2 min read
How to Drop rows in DataFrame by conditions on column values?
In this article, we are going to see several examples of how to drop rows from the dataframe based on certain conditions applied on a column. Pandas provide data analysts a way to delete and filter data frame using dataframe.drop() method. We can use this method to drop such rows that do not satisfy the given conditions. Let's create a Pandas dataf
3 min read
Count rows based on condition in Pyspark Dataframe
In this article, we will discuss how to count rows based on conditions in Pyspark dataframe. For this, we are going to use these methods: Using where() function.Using filter() function. Creating Dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSes
4 min read
Python | Creating a Pandas dataframe column based on a given condition
While operating on data, there could be instances where we would like to add a column based on some condition. There does not exist any library function to achieve this task directly, so we are going to see how we can achieve this goal. In this article, we will see how to create a Pandas dataframe column based on a given condition in Python. Proble
8 min read
How to select rows from a dataframe based on column values ?
Prerequisite: Pandas.Dataframes in Python In this article, we will cover how we select rows from a DataFrame based on column values in Python. The rows of a Dataframe can be selected based on conditions as we do use the SQL queries. The various methods to achieve this is explained in this article with examples. Importing Dataset for demonstration T
5 min read
Removing duplicate rows based on specific column in PySpark DataFrame
In this article, we are going to drop the duplicate rows based on a specific column from dataframe using pyspark in Python. Duplicate data means the same data based on some condition (column values). For this, we are using dropDuplicates() method: Syntax: dataframe.dropDuplicates(['column 1','column 2','column n']).show() where, dataframe is the in
1 min read
Filtering rows based on column values in PySpark dataframe
In this article, we are going to filter the rows based on column values in PySpark dataframe. Creating Dataframe for demonstration: C/C++ Code # importing module import spark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appName('spar
2 min read
Drop rows from Pandas dataframe with missing values or NaN in columns
Pandas provides various data structures and operations for manipulating numerical data and time series. However, there can be cases where some data might be missing. In Pandas missing data is represented by two value: None: None is a Python singleton object that is often used for missing data in Python code. NaN: NaN (an acronym for Not a Number),
4 min read
Drop a list of rows from a Pandas DataFrame
Let us see how to drop a list of rows in a Pandas DataFrame. We can do this using the Pandas drop() function. We will also pass inplace = True and axis=0 to denote row, as it makes the changes we make in the instance stored in that instance without doing any assignment. Creating Dataframe to drop a list of rows C/C++ Code # import the module import
3 min read
three90RightbarBannerImg