Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Steps
- Make two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
- Print input DataFrame, df.
- Initialize a variable nth_row.
- Use iloc() method to get nth row.
- Print the returned DataFrame.
Example
import pandas as pd
df = pd.DataFrame(
dict(
name=['John', 'Jacob', 'Tom', 'Tim', 'Ally'],
marks=[89, 23, 100, 56, 90],
subjects=["Math", "Physics", "Chemistry", "Biology", "English"]
)
)
print "Input DataFrame is:\n", df
nth_row = 3
df = df.iloc[nth_row]
print "Row ", nth_row, "of the DataFrame is: \n", df
Output
Input DataFrame is:
name marks subjects
0 John 89 Math
1 Jacob 23 Physics
2 Tom 100 Chemistry
3 Tim 56 Biology
4 Ally 90 English
Row 3 of the DataFrame is:
name Tim
marks 56
subjects Biology
Name: 3, dtype: objectAdvertisements