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", dfOutput
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: object