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, say column names are: ‘Name’, ‘Age’, ‘City’, and ‘Section’.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Example 1 : Find the location of an element in the dataframe.
Now let’s understand how the function getIndexes() works. The isin(), dataframe/series.any(), accepts values and returns a dataframe with boolean values. This boolean dataframe is of a similar size as the first original dataframe. The value is True at places where given element exists in the dataframe, otherwise False. Then find the names of columns that contain element 22. We can accomplish this by getting names of columns in the boolean dataframe which contains True. Now in the boolean dataframe we iterate over each of the selected columns and for each column, we find rows with True. Now, these combinations of column names and row indexes where True exists are the index positions of 22 in the dataframe. This is how getIndexes() founds the exact index positions of the given element & stores each position in the form of (row, column) tuple. Finally, it returns a list of tuples representing its index positions in the dataframe.
Example 2: Find location of multiple elements in the DataFrame.