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
How to access a group of rows in a Pandas DataFrame?
To access a group of rows in a Pandas DataFrame, we can use the loc[] indexer. For example, if we use df.loc[2:5], then it will select all the rows from index 2 to 5 (inclusive).
Using loc[] for Row Selection
The loc[] method allows label-based indexing and supports slice notation for selecting consecutive rows ?
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0, 7, 0, 5, 2],
"y": [4, 7, 5, 1, 5, 1, 4, 7],
"z": [9, 3, 5, 1, 5, 1, 9, 3]
}
)
print("Input DataFrame is:")
print(df)
Input DataFrame is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 4 7 5 5 5 0 1 1 6 5 4 9 7 2 7 3
Selecting Rows 2 to 5
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0, 7, 0, 5, 2],
"y": [4, 7, 5, 1, 5, 1, 4, 7],
"z": [9, 3, 5, 1, 5, 1, 9, 3]
}
)
selected_rows = df.loc[2:5]
print("Selected rows (2 to 5):")
print(selected_rows)
Selected rows (2 to 5): x y z 2 7 5 5 3 0 1 1 4 7 5 5 5 0 1 1
Alternative Methods
Using iloc[] for Position-Based Selection
Use iloc[] for integer position-based indexing ?
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0, 7, 0, 5, 2],
"y": [4, 7, 5, 1, 5, 1, 4, 7],
"z": [9, 3, 5, 1, 5, 1, 9, 3]
}
)
# Select rows by position (2 to 5, exclusive end)
selected_rows = df.iloc[2:6]
print("Selected rows using iloc[2:6]:")
print(selected_rows)
Selected rows using iloc[2:6]: x y z 2 7 5 5 3 0 1 1 4 7 5 5 5 0 1 1
Comparison
| Method | Type | End Inclusive? | Use Case |
|---|---|---|---|
loc[] |
Label-based | Yes | When using index labels |
iloc[] |
Position-based | No | When using integer positions |
Conclusion
Use df.loc[start:end] for label-based row selection with inclusive endpoints. Use df.iloc[start:end] for position-based selection with exclusive endpoints.
Advertisements
