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]
Additional Resources
How to Get Cell Value from Pandas DataFrame
How to Rename Index in Pandas DataFrame
How to Sort Columns by Name in Pandas