Find location of an element in Pandas dataframe in Python
Last Updated :
21 Dec, 2023
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.
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]
How to find location of multiple elements in the DataFrame
There are several ways to find the location of multiple elements in a DataFrame. Below are three common approaches.
Using isin()
The code snippet creates a list of target students you want to find. It then uses the isin()
method on the 0th
column to select rows. Finally, it retrieves the index of those rows using the .index
attribute.
Python3
import pandas as pd
index_list = students[students.isin(['Ankit', 'Swapnil','Delhi'])]
print(index_list)
Output:
0 1 2 3
0 Ankit NaN Delhi NaN
1 Swapnil NaN Delhi NaN
2 NaN NaN NaN NaN
3 NaN NaN Delhi NaN
4 NaN NaN NaN NaN
Similar Reads
Find Exponential of a column in Pandas-Python Let's see how to find Exponential of a column in Pandas Dataframe. First, let's create a Dataframe: Python3 # importing pandas and # numpy libraries import pandas as pd import numpy as np # creating and initializing a list values= [ ['Rohan', 5, 50.59], ['Elvish', 2, 90.57], ['Deepak', 10, 98.51], [
2 min read
Python | Pandas Dataframe.iat[ ] Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas iat[] method is used to return data in a dataframe at the passed location. The
2 min read
Python | Pandas DataFrame.isin() In this article, we will explore the Pandas DataFrame.isin() method provided by the Pandas library in Python. Python is widely recognized for its proficiency in data analysis, largely attributed to its exceptional ecosystem of data-centric packages. Among these, Pandas stands out as an essential too
2 min read
How to get nth row in a Pandas DataFrame? Pandas Dataframes are basically table format data that comprises rows and columns. Now for accessing the rows from large datasets, we have different methods like iloc, loc and values in Pandas. The most commonly used method is iloc(). Let us consider a simple example.Method 1. Using iloc() to access
4 min read
Python | Pandas dataframe.idxmin() Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.idxmin() function returns index of first occurrence of minimum over r
2 min read
Check if a value exists in a DataFrame using in & not in operator in Python-Pandas In this article, Letâs discuss how to check if a given value exists in the dataframe or not.Method 1 : Use in operator to check if an element exists in dataframe.  Python3 # import pandas library import pandas as pd # dictionary with list object in values details = { 'Name' : ['Ankit', 'Aishwarya',
3 min read
Label-based indexing to the Pandas DataFrame Indexing plays an important role in data frames. Sometimes we need to give a label-based "fancy indexing" to the Pandas Data frame. For this, we have a function in pandas known as pandas.DataFrame.lookup(). The concept of Fancy Indexing is simple which means, we have to pass an array of indices to a
3 min read
Python | Pandas Dataframe.at[ ] Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas at[] is used to return data in a dataframe at the passed location. The passed l
2 min read
How to Get First Column of Pandas DataFrame? Getting the first column of a Pandas DataFrame is a frequent task when working with tabular data. Pandas provides multiple simple and efficient ways to extract a column, whether you want it as a Series (1D) or as a DataFrame (2D). Letâs explore the common methods to retrieve the first column of a Da
3 min read
Dataframe Attributes in Python Pandas In this article, we will discuss the different attributes of a dataframe. Attributes are the properties of a DataFrame that can be used to fetch data or any information related to a particular dataframe. The syntax of writing an attribute is: DataFrame_name.attribute These are the attributes of the
11 min read