Search for a value anywhere in a pandas dataframe

Given a pandas dataframe, we have to search for a value anywhere.
Submitted by Pranit Sharma, on October 16, 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.

Problem statement

Suppose we are given with as DataFrame with multiple columns and multiple values and we need to check for a specific value int this pandas DataFrame despite knowing about the column which contains this value.

Searching for a value anywhere in a pandas dataframe

For this purpose, we will perform an equality comparison on the entire DataFrame. pandas.DataFrame.eq() is a method that checks for any specific value passed inside it as a parameter in a DataFrame. We will use this method for the entire DataFrame and return the rows where the specific value is found.

Let us understand with the help of an example,

Python program to search for a value anywhere in a pandas dataframe

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'A':[10,9,8,20,23,30],
    'B':[1,2,7,5,11,20],
    'C':[1,2,3,4,5,90]
}

# Creating a DataFrame
df = pd.DataFrame(d)

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

# Declaring a value that we need to find
val = 5

# Finding our value in dataframe
res = df[df.eq(val).any(1)]

# Display result
print("Result:\n",res)

Output

The output of the above program is:

Example: Search for a value anywhere in a pandas dataframe

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.