Return Row Indices where Column Matches Value in Python (Example Code)

In this article, I’ll demonstrate how to return the indices of rows with a certain value in a columns of a pandas DataFrame in the Python programming language.

Preparing the Example

import pandas as pd                                 # Load pandas library
my_df = pd.DataFrame({'A':['a', 'b', 'a', 'b'],    # Construct DataFrame in Python
                      'B':['hey', 'juhu', 'hi', 'yoyo'],
                      'C':[1, 0, 2, 1]})
print(my_df)                                       # Display DataFrame in console
#    A     B  C
# 0  a   hey  1
# 1  b  juhu  0
# 2  a    hi  2
# 3  b  yoyo  1

Example: Get Index of Matching Rows in pandas DataFrame Column

my_df.index[my_df['C'] == 1].tolist()              # Returning indices
# [0, 3]

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.
You need to agree with the terms to proceed