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 get nth row in a Pandas DataFrame?
To get the nth row in a Pandas DataFrame, we can use the iloc[] method. For example, df.iloc[4] will return the 5th row because row numbers start from 0.
Syntax
df.iloc[n]
Where n is the index position (0-based) of the row you want to access.
Creating a Sample DataFrame
Let's create a DataFrame with student information ?
import pandas as pd
df = pd.DataFrame({
'name': ['John', 'Jacob', 'Tom', 'Tim', 'Ally'],
'marks': [89, 23, 100, 56, 90],
'subjects': ["Math", "Physics", "Chemistry", "Biology", "English"]
})
print("Input DataFrame:")
print(df)
Input DataFrame:
name marks subjects
0 John 89 Math
1 Jacob 23 Physics
2 Tom 100 Chemistry
3 Tim 56 Biology
4 Ally 90 English
Getting the nth Row
Use iloc[] to access the row at index 3 (4th row) ?
import pandas as pd
df = pd.DataFrame({
'name': ['John', 'Jacob', 'Tom', 'Tim', 'Ally'],
'marks': [89, 23, 100, 56, 90],
'subjects': ["Math", "Physics", "Chemistry", "Biology", "English"]
})
nth_row = 3
result = df.iloc[nth_row]
print(f"Row {nth_row} of the DataFrame:")
print(result)
Row 3 of the DataFrame: name Tim marks 56 subjects Biology Name: 3, dtype: object
Multiple Methods
Using iloc[] for Multiple Rows
Get multiple rows by passing a list of indices ?
import pandas as pd
df = pd.DataFrame({
'name': ['John', 'Jacob', 'Tom', 'Tim', 'Ally'],
'marks': [89, 23, 100, 56, 90],
'subjects': ["Math", "Physics", "Chemistry", "Biology", "English"]
})
# Get rows 1, 3, and 4
selected_rows = df.iloc[[1, 3, 4]]
print("Selected rows:")
print(selected_rows)
Selected rows:
name marks subjects
1 Jacob 23 Physics
3 Tim 56 Biology
4 Ally 90 English
Using loc[] with Row Labels
Use loc[] when working with labeled indices ?
import pandas as pd
df = pd.DataFrame({
'name': ['John', 'Jacob', 'Tom', 'Tim', 'Ally'],
'marks': [89, 23, 100, 56, 90],
'subjects': ["Math", "Physics", "Chemistry", "Biology", "English"]
}, index=['A', 'B', 'C', 'D', 'E'])
# Get row with label 'C'
result = df.loc['C']
print("Row with label 'C':")
print(result)
Row with label 'C': name Tom marks 100 subjects Chemistry Name: C, dtype: object
Comparison
| Method | Usage | Best For |
|---|---|---|
iloc[n] |
Position-based | Integer positions (0, 1, 2...) |
loc[label] |
Label-based | Custom row labels |
Conclusion
Use iloc[n] to get the nth row by position, or loc[label] for labeled indices. Both methods return a Series object containing the row data.
Advertisements
