Python Pandas: Get Index Of Rows Where Column Matches Certain Value

To get the index of rows where a column matches a certain value in Python Pandas, you can use the loc function along with a condition. Here’s an example:

import pandas as pd

# create a sample dataframe
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
        'Age': [25, 30, 35, 40],
        'City': ['New York', 'London', 'Paris', 'Tokyo']}
df = pd.DataFrame(data)

# get the index of rows where the 'City' column matches 'Paris'
indexes = df.loc[df['City'] == 'Paris'].index

# print the indexes
print(indexes)

Output:

Int64Index([2], dtype='int64')

In this example, the loc function is used with a condition df['City'] == 'Paris' to filter the rows where the ‘City’ column matches the value ‘Paris’. The index attribute is then used to retrieve the indexes of the matching rows.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!