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 |
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 |
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] |
my_df.index[my_df['C'] == 1].tolist() # Returning indices # [0, 3]