Removing Rows on Count condition

Given a pandas dataframe, we have to remove rows from it on count condition.
Submitted by Pranit Sharma, on November 21, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Removing Rows from pandas dataframe on Count condition

Suppose we are given a DataFrame with some columns representing the information of some cities.

We need to remove all the rows from this DataFrame occurrence of any city name that is less than a particular number.

For this purpose, we will first group the city name column and use a transform function inside which we will pass a condition.

Let us understand with the help of an example,

Python code to remove rows from pandas DataFrame on count condition

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {

# Creating dataframe
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Grouping city name and filtering rows
res = df.groupby('city_name').filter(lambda x : len(x)>1)

# Display result


Example: Removing Rows on Count condition

Python Pandas Programs »


Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.