Display the first and last rows of a DataFrame with head() and tail()
Expt. No.14
Page No.28
head() and tail() on a DataFrame
Aim
To write a Python program that displays the first and last rows of a DataFrame using head() and tail().
Concepts used
Algorithm
- Create a DataFrame of 8 cities with their temperature.
- Display head(), head(3) and tail(2).
Program
# head() and tail() on a DataFrame import pandas as pd df = pd.DataFrame({"City": ["Delhi", "Mumbai", "Chennai", "Kolkata", "Jaipur", "Bhopal", "Patna", "Shimla"], "Temp": [31, 30, 33, 29, 34, 28, 30, 18]})print("head():")print(df.head())print("head(3):")print(df.head(3))print("tail(2):")print(df.tail(2))
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python dataframe_head_tail.py
head():
City Temp
0 Delhi 31
1 Mumbai 30
2 Chennai 33
3 Kolkata 29
4 Jaipur 34
head(3):
City Temp
0 Delhi 31
1 Mumbai 30
2 Chennai 33
tail(2):
City Temp
6 Patna 30
7 Shimla 18
✓ Printed by running this program, not typed by hand.
Result
head() displayed the first 5 cities, head(3) the first 3 and tail(2) the last 2 (Patna and Shimla), each with its row label.
Viva voce: what the examiner may ask
01How many rows does head() show by default?
5.
02Why are head() and tail() useful?
To look quickly at the start or end of a large DataFrame, such as one read from a CSV file.
03Do they change the DataFrame?
No.
Variations for the lab test
- Display the last 4 rows.
- Display the first row only.
- Display all rows except the last 3 with
head(-3).
! Common mistake Writing
df.head(3) expecting rows with index 3 shows the first three rows (0, 1, 2), not row 3.