Home »
Python »
Python Programs
Filter out groups with a length equal to one
Given a pandas dataframe, we have to filter out groups with a length equal to one.
By Pranit Sharma Last updated : October 03, 2023
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.
Problem statement
Suppose we are given a DataFrame and we need to create a groupby object and then we will select all the groups with size > 1.
Filtering out groups with a length equal to one
The groupby() method is a simple but very useful concept in pandas. By using groupby, we can create grouping of certain values and perform some operations on those values. It splits the object, applies some operations, and then combines them to create a group hence large amounts of data and computations can be performed on these groups.
On this grouped object, we will apply the lambda function inside which we will pass the specific condition to filter out the Data.
Let us understand with the help of an example,
Python program to filter out groups with a length equal to one
# Importing pandas package
import pandas as pd
# Importing numpy package
import numpy as np
# Creating a dictionary
d = {
'a':['Hello','Hi','Hello','Hello'],
'b':[0,1,2,3]
}
# Creating DataFrame
df = pd.DataFrame(d)
# Display original DataFrame
print("Original DataFrame:\n",df,"\n")
# Creating groupby object
group = df.groupby('a')
# Filtering the data
res = group.filter(lambda x: len(x) > 1)
# Display result
print("Result:\n",res)
Output
The output of the above program is:
Python Pandas Programs »