You should use loc to select by label:

FIRST = 3
LAST = 8

df_selected = df[df['fruit'] == 'pear']
out = df.loc[FIRST:LAST]

Or:

idx = df[df['fruit'] == 'pear'].index
out = df.loc[idx.min():idx.max()]

NB. since loc includes both ends, you do not need the +1.

Output:

   number   fruit  color letter
3       4    pear    red      B
4       5    pear  green      A
5       6    pear   blue      B
6       7  banana    red      A
7       8  banana  green      B
8       9    pear   blue      A

When using df_selected[1:2], this behaves like iloc and selects from the fourth to the ninth position (so just the row with label 8).

alternative

If your goal is to select all values between the first and last match, you could also use boolean indexing:

m = df['fruit'].eq('pear')
out = df[m.cummax()&m[::-1].cummax()]

How it works:

   number   fruit  color letter      m  m.cummax()  m[::-1].cummax()      &
0       1   apple    red      A  False       False              True  False
1       2   apple  green      B  False       False              True  False
2       3   apple   blue      A  False       False              True  False
3       4    pear    red      B   True        True              True   True
4       5    pear  green      A   True        True              True   True
5       6    pear   blue      B   True        True              True   True
6       7  banana    red      A  False        True              True   True
7       8  banana  green      B  False        True              True   True
8       9    pear   blue      A   True        True              True   True
9      10   apple    red      B  False        True             False  False
Answer from mozway on Stack Overflow
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ user_guide โ€บ indexing.html
Indexing and selecting data โ€” pandas 3.0.5 documentation
A callable function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above). A tuple of row (and column) indices whose elements are one of the above inputs. See more at Selection by Position, Advanced Indexing and Advanced Hierarchical.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ pandas โ€บ indexing-and-selecting-data-with-pandas
Indexing and Selecting Data with Pandas - GeeksforGeeks
The .iloc[] function is used for position-based indexing. It allows us to access rows and columns by their integer positions. It is similar to .loc[] but only accepts integer-based indices to specify rows and columns. To select a single row using .iloc[] provide the integer position of the row: ... import pandas as pd data = pd.read_csv("/content/nba.csv", index_col="Name") row = data.iloc[3] print(row)
Published: April 28, 2026
Discussions

How to select rows from a Pandas DataFrame using index? - Stack Overflow
I am trying to select rows from a Pandas DataFrame, using the integer index values. This does not work, and I obtain out of index errors. This suggests to me that performing a selection of rows by... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Is there a way to address Pandas dataframe by column index instead of name?
# get the 1st entry of the 5th column result=df.iat[0,4] # Then check if it's a string isinstance(result,str) https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iat.html More on reddit.com
๐ŸŒ r/learnpython
12
0
December 12, 2020
Get index values from pandas multiindex
df.index.get_level_values(1).unique() or df.index.get_level_values(2).unique() depending on which level of the index you want. More on reddit.com
๐ŸŒ r/learnpython
4
1
February 27, 2021
pandas: How to use `.iloc` with multiindex?

I think this is the best so far. Thanks.

More on reddit.com
๐ŸŒ r/learnpython
10
3
February 2, 2019
๐ŸŒ
Kaggle
kaggle.com โ€บ code โ€บ residentmario โ€บ indexing-selecting-assigning
Indexing, Selecting & Assigning | Kaggle
April 21, 2023 - Explore and run AI code with Kaggle Notebooks | Using data from multiple data sources
๐ŸŒ
Statology
statology.org โ€บ home โ€บ how to select rows by index in a pandas dataframe
How to Select Rows by Index in a Pandas DataFrame
March 27, 2025 - Another useful way to select rows is by using boolean conditions on the index. This method gives you flexibility to filter rows based on specific conditions applied to the index values. Letโ€™s look at how to select rows where the index is greater than a certain value: import pandas as pd import numpy as np #make this example reproducible np.random.seed(0) #create DataFrame df = pd.DataFrame(np.random.rand(6,2), index=range(0,18,3), columns=['A', 'B']) #view DataFrame df A B 0 0.548814 0.715189 3 0.602763 0.544883 6 0.423655 0.645894 9 0.437587 0.891773 12 0.963663 0.383442 15 0.791725 0.528895 #select rows where index is greater than 6 df[df.index > 6] A B 9 0.437587 0.891773 12 0.963663 0.383442 15 0.791725 0.528895
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.DataFrame.index.html
pandas.DataFrame.index โ€” pandas 3.0.5 documentation
The index is used for label-based access and alignment, and can be accessed or modified using this attribute.
Find elsewhere
๐ŸŒ
Medium
medium.com โ€บ @amit25173 โ€บ how-to-use-pandas-get-row-by-index-b01fa9339cdf
How to Use pandas Get Row by Index? | by Amit Yadav | Medium
April 12, 2025 - You want to access rows, and pandas allows you to do this effortlessly. Letโ€™s dive into how you can achieve this with some practical examples. ... To get a specific row by its index, you can use the .loc or .iloc methods. The main difference is that .loc accesses rows based on label-based indexing, while .iloc is entirely integer-location-based.
๐ŸŒ
CodeSignal
codesignal.com โ€บ learn โ€บ courses โ€บ pandas-basics-and-dataframe-manipulation โ€บ lessons โ€บ indexing-and-selecting-data-in-pandas
Indexing and Selecting Data in Pandas
Note that we set the "Name" column as index. In loc, we use labels (which Is the name-indices and column names) to select the required data.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python_pandas โ€บ python_pandas_indexing_and_selecting_data.htm
Python Pandas - Indexing and Selecting Data
loc takes two single/list/range operator separated by ','. The first one indicates the row and the second one indicates columns. Here is a basic example that selects all rows for a specific column using the loc indexer. #import the pandas library and aliasing as pd import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(8, 4), index = ['a','b','c','d','e','f','g','h'], columns = ['A', 'B', 'C', 'D']) print("Original DataFrame:\n", df) #select all rows for a specific column print('\nResult:\n',df.loc[:,'A'])
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-get-rows-index-names-in-pandas-dataframe
How to get rows/index names in Pandas dataframe - GeeksforGeeks
July 11, 2025 - Now, let's print the total count of index. ... # Import pandas package import pandas as pd # making data frame data = pd.read_csv("nba.csv") row_count = 0 # iterating over indices for col in data.index: row_count += 1 # print the row count print(row_count)
๐ŸŒ
Saturn Cloud
saturncloud.io โ€บ blog โ€บ how-to-find-the-index-of-a-value-anywhere-in-a-pandas-dataframe
How to Find the Index of a Value Anywhere in a Pandas DataFrame | Saturn Cloud Blog
May 1, 2026 - As a data scientist or software engineer you may find yourself working with large datasets and needing to quickly locate the index of a specific value in a Pandas DataFrame. This can be a time-consuming task if done manually but thankfully Pandas offers an easy and efficient way to accomplish ...
๐ŸŒ
Arab Psychology
scales.arabpsychology.com โ€บ home โ€บ how can i select columns by index in a pandas dataframe?
How Can I Select Columns By Index In A Pandas DataFrame?
July 2, 2024 - Pandas is a popular Python library used for data analysis and manipulation. One of its key features is the ability to select columns in a DataFrame by their index. This means that instead of using the column names, which can be prone to human error, you can select columns by their numerical position.
๐ŸŒ
LinkedIn
linkedin.com โ€บ advice โ€บ 0 โ€บ how-do-you-select-subsets-data-pandas-dataframe-using-fkvqe
Master Pandas Indexing: Select Data Subsets with Ease
April 10, 2024 - Discover 100 collaborative articles on domains such as Marketing, Public Administration, and Healthcare. Our expertly curated collection combines AI-generated content with insights and advice from industry experts, providing you with unique perspectives and up-to-date information on many skills ...
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ pandas โ€บ pandas get index from dataframe
Pandas Get Index from DataFrame - Spark By {Examples}
November 6, 2024 - How to get an index from Pandas DataFrame? DataFrame.index property is used to get the index from the DataFrame. Pandas Index is an immutable sequence
๐ŸŒ
Medium
giulio-laurenti.medium.com โ€บ indexing-pandas-dataframes-59c013790832
Indexing Pandas DataFrames. How to select data from a DataFrame | by Giulio Laurenti, PhD | Medium
April 1, 2026 - Indexing is the process of selecting a specific subset of data from a DataFrame. In this post, we will learn how to select specific columns and rows from a DataFrame using Pandas.
๐ŸŒ
APXML
apxml.com โ€บ courses โ€บ intermediate-python-programming-ml โ€บ chapter-3-data-manipulation-pandas โ€บ pandas-indexing-selection
Pandas Data Indexing and Selection (loc, iloc)
Using [] for row selection via slicing works, but for clarity and avoiding potential confusion, especially when dealing with integer indices, Pandas offers more explicit methods: .loc and .iloc. The .loc indexer is used for selection primarily based on labels (index names and column names). It provides a very explicit way to select data. ... Slice of rows by label: df.loc['2023-01-02':'2023-01-04'] (returns a DataFrame).
๐ŸŒ
Analytics Vidhya
analyticsvidhya.com โ€บ home โ€บ indexing and selecting data in python โ€“ how to slice, dice for pandas series and dataframe
Indexing and Selecting Data in Python - How to slice, dice for Pandas Series and DataFrame
October 27, 2024 - The first line is to want the output of the first four rows and the second line is to find the output of two to three rows and column indexing of B and C.# Integer slicing print (df1.iloc[:4]) print (df1.iloc[2:4, 1:3]) .ixis used for both labels and integer-based. Besides pure label based and integer-based, Pandas provides a hybrid method for selections and subsetting the object using the .ix() operator.import pandas as pd import numpy as npdf2 = pd.DataFrame(np.random.randn(8, 3), columns = [โ€˜Aโ€™, โ€˜Bโ€™, โ€˜Cโ€™])# Integer slicing print (df2.ix[:4])
๐ŸŒ
Wrighters
wrighters.io โ€บ home โ€บ indexing and selecting in pandas by callable
Indexing and Selecting in Pandas by Callable - wrighters.io
April 14, 2021 - In all of the discussion so far, weโ€™ve focused on the three main methods of selecting data in the two main pandas data structures, Series and DataFrame. ... We noted in the last entry in the series that all three can take a boolean vector as indexer to select data from the object.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_lists_access.asp
Python - Access List Items
By leaving out the end value, the range will go on to the end of the list: This example returns the items from "cherry" to the end: thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:]) Try it Yourself ยป ยท Specify negative indexes if you want to start the search from the end of the list:
๐ŸŒ
Finxter
blog.finxter.com โ€บ 5-best-ways-to-select-dataframe-rows-between-two-index-values-in-python-pandas
5 Best Ways to Select DataFrame Rows Between Two Index Values in Python Pandas โ€“ Be on the Right Side of Change
By specifying the starting and ending index labels, loc allows for index-based selection of rows within the specified range, including both endpoints. This functionality is uniquely suited for label-indexed rows allowing for an intuitive slicing operation. ... import pandas as pd # Create a ...