Display the first and last elements of a Series with head() and tail()
Expt. No.04
Page No.8
head() and tail() on a Series
Aim
To write a Python program that displays the first and last elements of a Series using head() and tail().
Concepts used
Algorithm
- Create a Series of 10 daily temperatures.
- Display head() (first 5), head(3) and tail(2).
Program
# head() and tail() on a Series import pandas as pd temp = pd.Series([31, 33, 30, 29, 34, 36, 35, 32, 30, 28], index=["D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "D10"])print("head():")print(temp.head())print("head(3):")print(temp.head(3))print("tail(2):")print(temp.tail(2))
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python series_head_tail.py
head():
D1 31
D2 33
D3 30
D4 29
D5 34
dtype: int64
head(3):
D1 31
D2 33
D3 30
dtype: int64
tail(2):
D9 30
D10 28
dtype: int64
✓ Printed by running this program, not typed by hand.
Result
head() showed the first 5 days, head(3) the first 3 and tail(2) the last 2 days (D9 and D10).
Viva voce: what the examiner may ask
01How many elements do head() and tail() show by default?
5.
02What does head(-3) return?
All elements except the last 3.
03Do head() and tail() change the Series?
No. They return a new view of some elements.
Variations for the lab test
- Display the last 4 days.
- Display all but the first 2 days with
tail(-2). - Display the first 3 days whose temperature is above 30 (use a condition, then head()).
! Common mistake Writing
temp.head[3] with square brackets raises TypeError; head is a method, so use head(3).