Pandas Get Index of Row in Python [6 Ways]

Are you searching for ways to get the row index in a Pandas dataframe? In this Python tutorial, I will explain different ways in which Pandas get index of row in Python with some illustrative examples.

To get the index of a row in Pandas, we can use the boolean indexing method, the loc method, and the get_loc method with the index object.

We can also use indirect methods that can help us to get the index of a row in Pandas like:

  1. iterrows
  2. query() function
  3. np.where() function

Let’s see all the methods with some examples for Pandas get index of row in Python:

1. Get index of row in Pandas Python using the boolean indexing

The boolean indexing in Pandas Python is a way where we use a boolean condition to filter and select specific rows in a DataFrame.

The index attribute of the DataFrame to find the index of the row in Pandas dataframe with the tolist() function that converts the result index to a list.

Here is the example that will give the index of the row in Python Pandas according to the condition provided.

import pandas as pd

employee_data = {'Name': ['Alice', 'Bob', 'Charlie', 'Bob'],
        'Age': [25, 30, 35, 45]}
df = pd.DataFrame(employee_data)

index_row = df.index[df['Name'] == 'Bob'].tolist()
print("Index of the row:", index_row)

Output:

Index of the row: [1, 3]

After implementing the code in the Python Pycharm editor, I have taken the below screenshot:

Pandas Get Index of Row in Python

2. How to get the index of a row in Pandas using index.get_loc() method

The .index.get_loc() in Python allows us to obtain the integer position of an index label directly. By using this method, we can find the row index by using the value found in the Name column.

READ:  Python Turtle Dot - Helpful Guide

Here is the code to do so:

import pandas as pd

cities_data = {'City': ['New York', 'Austin', 'Chicago', 'Houston', 'Phoenix'],
        'Population (millions)': [8.4, 3.9, 2.7, 2.3, 1.7],
        'State': ['New York', 'Texas', 'Illinois', 'Texas', 'Arizona']}
cities_df = pd.DataFrame(cities_data)

row_index = cities_df.index.get_loc(cities_df[cities_df['State'] == 'Texas'].index[0])
print("Index using Index of a Value is:", row_index)

Output: In this code, we first find the index label of the row with the Name column that is ‘State’ equal to ‘Texas’, and then we use .index.get_loc() to get its integer location.

Index using Index of a Value is: 1

The screenshot is mentioned below:

dataframe get index of row in Python

3. Pandas dataframe get index of row using loc method

The loc method in Python Pandas is label-based, and it allows us to access a group of rows and columns by labels. This method can be used along with the Index property to obtain the index of a row based on the label.

Here is an instance that illustrates the use of the loc method to get the index of the row in Python.

import pandas as pd

cities_data = {'City': ['New York', 'Austin', 'Chicago', 'Houston', 'Phoenix'],
        'State': ['New York', 'Texas', 'Illinois', 'Texas', 'Arizona']}
df = pd.DataFrame(cities_data)

index_row = df.index[df['State'] == 'Texas'].tolist()[:]
print("Index of the row is:", index_row)

Output:

Index of the row is: [1, 3]

Here, is the screenshot of the source code:

python dataframe get index of row

4. Find the index of row in Pandas using iterrows

The iterrows method in Python allows us to iterate over Pandas DataFrame rows as (index, Series) pairs. While it is not the most efficient method, it provides a straightforward way to obtain the index.

Down is the example:

import pandas as pd

USA_data = {'Capital': ['Sacramento', 'Columbus', 'Albany', 'Austin', 'Phoenix'],
        'State': ['California', 'Ohio', 'New York', 'Texas', 'Arizona']}
df = pd.DataFrame(USA_data)

for index, row in df.iterrows():
    if row['Capital'] == 'Albany':
        index_row = index
print("Index of row is:", index_row)

Output:

Index of row is: 2

The screenshot mentioned below is taken after implementing it to in Pycharm editor.

pandas get row index in Python

5. Get row index Pandas using the query() method

The query() method in Pandas allows us to filter rows based on a query expression. While it doesn’t directly provide the index of a row, we can use it with other methods like index to achieve this.

READ:  Attributeerror: Module 'tensorflow' has no attribute 'trainable_variables'

Here’s an example using the query() method to get the index of a row in Pandas:

import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
        'Age': [25, 30, 35, 28, 32]}
df = pd.DataFrame(data)

query_result = df.query("Name == 'Bob'")
index_row = query_result.index[0]
print("Index of the row is:", index_row)

Output:

Index of the row is: 1

After executing, I have taken the below screenshot:

how to get index of a row in pandas in Python

6. Pandas get index of row in Python using the np.where() function

Another way to obtain the index is to supply a condition to the numpy.where() method. The np.where() function is used to find the indices of the items in an input array when the specified condition is True.

Let’s see an example to do so:

import pandas as pd
import numpy as np

data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
        'Age': [25, 30, 35, 28, 32]}
df = pd.DataFrame(data)

print(list(np.where(df["Age"] > 30)))

Output:

[array([2, 4], dtype=int64)]

The screenshot is mentioned below:

python pandas get index of row

Conclusion

This article explains six different ways in Pandas to get index of row in Python. Understanding these methods such as boolean indexing, get_loc() method, loc() method, iterrows, query() or np.where() function can be very helpful to solve their problem wherever dealing with the “Pandas Get Index of Row in Python.”

The choice of the method depends upon the requirement of the coder. I hope you like this.

You may also like to read: