How to get index of rows whose column matches value?

To get the index of rows whose column matches a certain value, you can use the .loc[] method in pandas, which allows you to select the row labels that match a certain value in a certain column. The syntax is dataframe.loc[dataframe[column] == value], where column is the name of the column that contains the values you are looking for and value is the value you want to find. This will return a list of the row indexes that contain the value in the specified column.


You can use the following syntax to get the index of rows in a pandas DataFrame whose column matches specific values:

df.index[df['column_name']==value].tolist()

The following examples show how to use this syntax in practice with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D'],
                   'points': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
df

team	points	rebounds
0	A	5	11
1	A	7	8
2	A	7	10
3	B	9	6
4	B	12	6
5	C	9	5
6	C	9	9
7	D	4	12

Example 1: Get Index of Rows Whose Column Matches Value

The following code shows how to get the index of the rows where one column is equal to a certain value:

#get index of rows where 'points' column is equal to 7
df.index[df['points']==7].tolist()

[1, 2]

This tells us that the rows with index values 1 and 2 have the value ‘7’ in the points column.

Note that we can also use the less than and greater than operators to find the index of the rows where one column is less than or greater than a certain value:

#get index of rows where 'points' column is greater than 7
df.index[df['points']>7].tolist()

[3, 4, 5, 6]

This tells us that the rows with index values 3, 4, 5, and 6 have a value greater than ‘7’ in the points column.

Example 2: Get Index of Rows Whose Column Matches String

The following code shows how to get the index of the rows where one column is equal to a certain string:

#get index of rows where 'team' column is equal to 'B'
df.index[df['team']=='B'].tolist()

[3, 4]

This tells us that the rows with index values 3 and 4 have the value ‘B’ in the team column.

Example 3: Get Index of Rows with Multiple Conditions

The following code shows how to get the index of the rows where the values in multiple columns match certain conditions:

#get index of rows where 'points' is equal to 7 or 12
df.index[(df['points']==7) | (df['points']==12)].tolist()

[1, 2, 4]

#get index of rows where 'points' is equal to 9 and 'team' is equal to 'B'
df.index[(df['points']==9) & (df['team']=='B')].tolist()

[3]

x