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?
Submitted by Pranit Sharma, on November 09, 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.

Finding rows where all the columns are equal

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.

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 code 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:

Example: Find Rows Where all Columns Equal

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




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

© https://www.includehelp.com some rights reserved.