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 OverflowPandas
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
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
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
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
pandas: How to use `.iloc` with multiindex?
I think this is the best so far. Thanks.
More on reddit.com02:31
Pandas - Select Rows by Index Name or Label - YouTube
03:01
Select Rows of pandas DataFrame by Index in Python (2 Examples) ...
15:12
Pandas Dataframe Index & Selecting Data | Python Pandas Tutorial ...
Pandas Fundamentals | Indexing & Filtering
Selection in Pandas is easy!
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.
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'])
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 ...
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 ...