Python Pandas: Get index of rows where column matches certain value
You can use the .loc
method to filter the DataFrame and get the boolean mask, and then use the .index
property to get the index of the rows that match the certain value. Here's an example:
import pandas as pd
# create a sample dataframe
df = pd.DataFrame({'A': [1, 2, 3, 4, 5],
'B': [2, 3, 4, 5, 6],
'C': [3, 4, 5, 6, 7]},
index=[100, 101, 102, 103, 104])
# find the rows where column 'B' has the value 3
match = df.loc[df['B'] == 3].index
print(match)
This will output the index of the rows where column 'B' has the value 3:
Int64Index([101], dtype='int64')
Watch a video course
Python - The Practical Guide
You can use the same approach to filter on multiple columns and multiple conditions. Example:
df.loc[(df['A']==1) & (df['B']==2)].index
It will return the rows index which has A = 1 and B = 2