How to find an element in Pandas Dataframe?
In a Pandas DataFrame, you can find the position of a specific element or check for its existence using various methods. Here are a few common ways. Let’s create a dataframe first and see each method one by one.
Python3
import pandas as pd # List of tuples students = pd.DataFrame([( 'Ankit' , 23 , 'Delhi' , 'A' ), ( 'Swapnil' , 22 , 'Delhi' , 'B' ), ( 'Aman' , 22 , 'Dehradun' , 'A' ), ( 'Jiten' , 22 , 'Delhi' , 'A' ), ( 'Jeet' , 21 , 'Mumbai' , 'B' ) ]) students |
Output:
0 1 2 3
0 Ankit 23 Delhi A
1 Swapnil 22 Delhi B
2 Aman 22 Dehradun A
3 Jiten 22 Delhi A
4 Jeet 21 Mumbai B
Using isin()
Method
The isin()
method returns a DataFrame of the same shape as the input, with True
at positions where the specified element exists.
Python3
# Check if 'Jiten' is in the DataFrame result = students.isin([ 'Jiten' ]) print (result) |
Output:
0 1 2 3
0 False False False False
1 False False False False
2 False False False False
3 True False False False
4 False False False False
Using any()
Method
The any()
method checks if the specified element exists in any column, returning a Boolean result.
indices[indices]
to filter only the columns with True
values. The loop then iterates over these columns, and for each column, it finds the row index where the value exists using students[col_index]. eq().idxmax(), where
.idxmax()
: Finds the index (row index) where the first occurrence of True
appears.
Python3
indices = (students = = 'Jiten' ). any () #using any to find index positions indices |
Output:
0 True
1 False
2 False
3 False
dtype: bool
Using NumPy’s where()
Function
Returns indices where a specified condition is met in the DataFrame, useful for finding the position of an element.
Python3
indices = np.where(students = = 'Jeet' ) # Extracting row and column indices row_indices, col_indices = indices[ 0 ], indices[ 1 ] print (row_indices, col_indices) |
Output:
[4] [0]
Find location of an element in Pandas dataframe in Python
In this article, we will see how to find the position of an element in the dataframe using a user-defined function. Let’s first Create a simple dataframe with a dictionary of lists.
Contact Us