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
Python Pandas - How to select multiple rows from a DataFrame
To select multiple rows from a DataFrame, you can use various methods including slicing with the : operator, loc[] for label-based selection, and iloc[] for position-based selection.
Creating a DataFrame
First, let's create a sample DataFrame to work with ?
import pandas as pd
# Create DataFrame
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],
index=['w', 'x', 'y', 'z'],
columns=['a', 'b'])
print("DataFrame...")
print(dataFrame)
DataFrame...
a b
w 10 15
x 20 25
y 30 35
z 40 45
Using Slicing with : Operator
Select multiple rows using integer positions with the slice operator ?
import pandas as pd
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],
index=['w', 'x', 'y', 'z'],
columns=['a', 'b'])
# Select first two rows (positions 0 and 1)
print("Select multiple rows using slicing...")
print(dataFrame[0:2])
Select multiple rows using slicing...
a b
w 10 15
x 20 25
Using loc[] for Label-Based Selection
Use loc[] to select rows by their index labels ?
import pandas as pd
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],
index=['w', 'x', 'y', 'z'],
columns=['a', 'b'])
# Select multiple rows by label
print("Select rows 'x' to 'z' using loc...")
print(dataFrame.loc['x':'z'])
# Select specific rows by labels
print("\nSelect specific rows by labels...")
print(dataFrame.loc[['w', 'z']])
Select rows 'x' to 'z' using loc...
a b
x 20 25
y 30 35
z 40 45
Select specific rows by labels...
a b
w 10 15
z 40 45
Using iloc[] for Position-Based Selection
Use iloc[] to select rows by their integer positions ?
import pandas as pd
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],
index=['w', 'x', 'y', 'z'],
columns=['a', 'b'])
# Select rows by integer positions
print("Select rows at positions 1 to 3 using iloc...")
print(dataFrame.iloc[1:3])
# Select specific rows by positions
print("\nSelect rows at positions 0 and 3...")
print(dataFrame.iloc[[0, 3]])
Select rows at positions 1 to 3 using iloc...
a b
x 20 25
y 30 35
Select rows at positions 0 and 3...
a b
w 10 15
z 40 45
Comparison of Methods
| Method | Type | Usage | Example |
|---|---|---|---|
df[0:2] |
Position-based | Simple slicing | First 2 rows |
df.loc['x':'z'] |
Label-based | Index labels | Rows from 'x' to 'z' |
df.iloc[1:3] |
Position-based | Integer positions | Rows at positions 1-2 |
Conclusion
Use slicing [start:end] for simple row selection, loc[] for label-based selection, and iloc[] for position-based selection. Choose the method that best fits your data indexing needs.
Advertisements
