Get Index of Rows with Match in Column in Python (Example)

 

In this Python tutorial you’ll learn how to return the indices of rows with a certain value.

Table of contents:

If you want to know more about these contents, keep reading…

 

Example Data & Libraries

We first have to import the pandas library.

import pandas as pd                                         # Import pandas library

Furthermore, have a look at the example data below:

data = pd.DataFrame({'x1':['a', 'b', 'c', 'd', 'e', 'f'],  # Create example DataFrame
                     'x2':[5, 2, 5, 5, 8, 1],
                     'x3':['A', 'B', 'C', 'D', 'E', 'F']})
print(data)                                                # Print example DataFrame

 

table 1 DataFrame get index rows match column python

 

Table 1 shows the structure of our example data – It is composed of six rows and the three columns “x1”, “x2”, and “x3”.

 

Example: Return Matching Row Indices Using index Attribute & tolist() Function

In this example, I’ll illustrate how to find the indices of all rows where the column x2 contains the value 5.

For this, we can use the index attribute of our pandas DataFrame in combination with the tolist function.

Have a look at the following Python code:

data.index[data['x2'] == 5].tolist()                       # Get row indices
# [0, 2, 3]

As you can see, a list containing the values 0, 2, and 3 has been returned to the console. These values are the row indices where the variable x2 matches the value 5.

 

Video, Further Resources & Summary

In case you need further info on the examples of this tutorial, I recommend having a look at the following video on my YouTube channel. In the video instruction, I’m explaining the Python programming syntax of this article.

 

 

Have a look at the following video on the techtipnow YouTube channel. The speaker of this video demonstrates how to use the tolist function and related commands in the Python programming language.

 

 

Also, you may want to read the related tutorials on this homepage.

 

In this Python tutorial you have learned how to return the indices of rows with a certain value in columns of a pandas DataFrame. In case you have further questions, don’t hesitate to let me know in the comments section. Furthermore, don’t forget to subscribe to my email newsletter for updates on new articles.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top