During my years working with large datasets in Python, I’ve found that selecting specific rows is one of the most frequent tasks you’ll perform.
Whether you are cleaning financial records or analyzing census data, knowing how to grab a row by its index is a fundamental skill.
In this tutorial, I will show you exactly how to get a row by index in Pandas using several efficient methods.
The Data We’ll Use
To make these examples practical, let’s use a dataset representing real estate listings across various US cities.
I’ve included the full code below so you can follow along in your own Jupyter Notebook or Python script.
import pandas as pd
# Creating a sample dataset of US Real Estate listings
data = {
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Philadelphia'],
'State': ['NY', 'CA', 'IL', 'TX', 'AZ', 'PA'],
'Avg_Home_Price': [850000, 920000, 310000, 260000, 450000, 280000],
'Inventory_Count': [1200, 950, 2100, 3200, 1500, 1800]
}
# We will use 'City' as our custom index for some examples
df = pd.DataFrame(data)
df_indexed = df.set_index('City')
print("Original DataFrame with Integer Index:")
print(df)Method 1: Use the .iloc[] Attribute (Position-Based)
In my experience, iloc is the most reliable way to select a row when you know its numerical position.
It stands for “integer location.” It doesn’t matter what your index labels are; iloc only cares about the order.
If I want to get the first city in our list (New York), I use index 0.
# Getting the first row (index 0)
first_row = df.iloc[0]
print("First Row Data:")
print(first_row)You can refer to the screenshot below to see the output.

You can also grab multiple rows by passing a list of integers. For instance, if I want the first and third rows:
# Selecting specific rows by integer position
subset = df.iloc[[0, 2]]
print(subset)Method 2: Use the .loc[] Attribute (Label-Based)
I often prefer loc when my DataFrame has a meaningful index, like city names or dates. Unlike iloc, loc looks for the actual label in the index column.
Let’s use our df_indexed version where the city name is the index. If I want to find the data for “Chicago,” I do this:
# Getting a row by its label
chicago_data = df_indexed.loc['Chicago']
print("Chicago Real Estate Data:")
print(chicago_data)You can refer to the screenshot below to see the output.

One thing I’ve noticed is that loc is much more readable for other developers who might review your code later. It’s clear what data you are fetching.
Method 3: Select Multiple Rows by Label Slicing
Another powerful feature of loc is slicing. I use this constantly when dealing with alphabetical or chronological data.
Note that in Pandas, label-based slicing is inclusive of the endpoint.
# Getting all rows from Los Angeles to Houston
slice_df = df_indexed.loc['Los Angeles':'Houston']
print("Slicing from LA to Houston:")
print(slice_df)You can refer to the screenshot below to see the output.

This is incredibly useful when you have a dataset sorted by US states and want to pull a specific range, like ‘Alabama’ through ‘California’.
Method 4: Get a Single Cell Value by Index
Sometimes, you don’t need the whole row. You might just need one specific value, like the average home price in Phoenix.
I recommend using at or iat for this because they are optimized for speed when accessing a single scalar value.
# Using .at for label-based single value access
phoenix_price = df_indexed.at['Phoenix', 'Avg_Home_Price']
print(f"The average home price in Phoenix is: ${phoenix_price}")You can refer to the screenshot below to see the output.

In high-performance applications, using .at instead of .loc can save a significant amount of processing time.
Method 5: Use the .xs() Method for Multi-Indexing
If you are working with complex US data, you might have a MultiIndex (e.g., State and City).
In those cases, I find the xs() (cross-section) method to be the cleanest way to extract data.
# Creating a MultiIndex
df_multi = df.set_index(['State', 'City'])
# Getting all cities in Texas (TX)
tx_data = df_multi.xs('TX', level='State')
print("Texas Cities Data:")
print(tx_data)Using xs allows you to bypass the complexity of slicing through multiple levels of an index.
Method 6: Select Rows Based on Boolean Indexing
While not strictly “getting by index label,” I often find that people ask for an index when they actually mean they want to filter by a value.
For example, if you want to find the row where the inventory count is highest in the US.
# Finding the row where Inventory_Count is greater than 2000
high_inventory = df[df['Inventory_Count'] > 2000]
print("High Inventory Cities:")
print(high_inventory)Handle Errors: What If the Index Doesn’t Exist?
One common mistake I see is trying to access an index that isn’t there. This will trigger a KeyError.
To write robust code, I always suggest checking if the index exists first, especially when dealing with user-inputted data.
target_city = 'Seattle'
if target_city in df_indexed.index:
print(df_indexed.loc[target_city])
else:
print(f"Data for {target_city} is not available in this dataset.")Summary of Differences
To help you choose the right tool for your project, here is a quick breakdown of the methods we covered:
- iloc: Best for when you know the numerical position (e.g., “give me the 5th row”).
- loc: Best for when you have unique labels (e.g., “give me the row for ‘California'”).
- at/iat: Use these for maximum speed when you only need a single value.
- xs: The go-to method for MultiIndex DataFrames.
I hope this guide makes it easier for you to navigate your DataFrames and extract the exact rows you need.
Pandas indexing can feel a bit overwhelming at first, but once you master loc and iloc, you’ll be able to handle almost any data extraction task.
You may also like to read:
- How to Convert Pandas Column to Datetime
- Pandas Convert Column to Integer
- How to Convert String to Datetime in Pandas
- How to Convert Pandas Column to List in Python

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.