Home »
Python »
Python Programs
Pandas Dataframe Find Rows Where all Columns Equal
In this article, we are going to learn how to find rows where all the columns are equal?
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 that has characters in it and we want a Boolean result by row that represents that if all columns for that row have the same value.
Finding rows where all the columns are equal
The best way to do this is to check all columns against the first column using DataFrame.eq().
We will use iloc[] property for filtering the columns and then put this result into DataFrame.eq().
The Pandas DataFrame.eq() is a wrapper used for the comparison of the value. It provides a convenient way to perform a comparison of dataframe objects with constant, series, or another data frame object.
Let us understand with the help of an example,
Python program to find rows where all the columns are equal
# Importing pandas package
import pandas as pd
# Importing numpy package
import numpy as np
# Creating a dictionary
d = {
'a':['A','A','A','A'],
'b':['C','C','A','A'],
'c':['B','B','B','B']
}
# Creating a DataFrame
df = pd.DataFrame(d)
# Display dataframe
print('Original DataFrame:\n',df,'\n')
# selecting dataframe
res = df.eq(df.iloc[:, 0], axis=0)
# Display result
print('Result:\n',res,'\n')
Output
The output of the above program is:
Python Pandas Programs »