Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Select DataFrame rows between two index values in Python Pandas
We can slice a Pandas DataFrame to select rows between two index values using Python's slice notation. This is useful when working with specific ranges of data in your DataFrame.
Basic Index Slicing
The simplest way to select rows between two index values is using the slice notation df[start:end] where the start is inclusive and end is exclusive ?
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
print("Input DataFrame is:")
print(df)
index_lower_limit = 1
index_upper_limit = 3
print("\nDataFrame between two index values:")
print(df[index_lower_limit:index_upper_limit])
Input DataFrame is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 DataFrame between two index values: x y z 1 2 7 3 2 7 5 5
Using iloc for Position-Based Selection
For more explicit position-based selection, use iloc which works with integer positions ?
import pandas as pd
df = pd.DataFrame(
{
"name": ["Alice", "Bob", "Charlie", "Diana", "Eve"],
"age": [25, 30, 35, 28, 32],
"city": ["NY", "LA", "Chicago", "Miami", "Boston"]
}
)
print("Original DataFrame:")
print(df)
print("\nRows between index 1 and 4 using iloc:")
print(df.iloc[1:4])
Original DataFrame:
name age city
0 Alice 25 NY
1 Bob 30 LA
2 Charlie 35 Chicago
3 Diana 28 Miami
4 Eve 32 Boston
Rows between index 1 and 4 using iloc:
name age city
1 Bob 30 LA
2 Charlie 35 Chicago
3 Diana 28 Miami
Working with Custom Index
When your DataFrame has a custom index, you can slice using the actual index values ?
import pandas as pd
df = pd.DataFrame(
{
"product": ["A", "B", "C", "D", "E"],
"price": [100, 150, 200, 250, 300]
},
index=['P001', 'P002', 'P003', 'P004', 'P005']
)
print("DataFrame with custom index:")
print(df)
print("\nRows between P002 and P004:")
print(df['P002':'P004'])
DataFrame with custom index:
product price
P001 A 100
P002 B 150
P003 C 200
P004 D 250
P005 E 300
Rows between P002 and P004:
product price
P002 B 150
P003 C 200
P004 D 250
Key Points
- Standard slicing
df[start:end]is inclusive of start, exclusive of end - Custom index slicing
df['start':'end']is inclusive of both start and end - Use
ilocfor position-based selection regardless of index type
Conclusion
Use df[start:end] for simple integer index slicing or df['start':'end'] for custom index values. The iloc method provides consistent position-based selection across all index types.
Advertisements
