Select, index and slice a Series by label and by position
Expt. No.05
Page No.10
Selecting and slicing a Series
Aim
To write a Python program that selects elements of a Series by label, slices it by label and by position, and filters it with a condition.
Concepts used
Algorithm
- Create a Series of marks with names as the index.
- Select one element by label and several with a list of labels.
- Slice by label (the end label is included) and by position (the end position is not).
- Display the elements greater than 60.
Program
# Selection, indexing and slicing of a Series import pandas as pd s = pd.Series([45, 78, 62, 91, 55], index=["Asha", "Bharat", "Chetan", "Divya", "Eshan"])print("Marks of Chetan:", s["Chetan"])print("Asha and Divya:")print(s[["Asha", "Divya"]])print("Label slice Bharat to Divya:")print(s["Bharat":"Divya"])print("Position slice 1 to 3:")print(s[1:3])print("Marks above 60:")print(s[s > 60])
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python series_selection_slicing.py
Marks of Chetan: 62
Asha and Divya:
Asha 45
Divya 91
dtype: int64
Label slice Bharat to Divya:
Bharat 78
Chetan 62
Divya 91
dtype: int64
Position slice 1 to 3:
Bharat 78
Chetan 62
dtype: int64
Marks above 60:
Bharat 78
Chetan 62
Divya 91
dtype: int64
✓ Printed by running this program, not typed by hand.
Result
The label slice "Bharat":"Divya" included Divya (3 elements), while the position slice 1:3 stopped before position 3 (Bharat and Chetan only). The condition kept the 3 students who scored above 60.
Viva voce: what the examiner may ask
01Is the end label included in a label slice?
Yes. s["Bharat":"Divya"] includes Divya.
02Is the end position included in a position slice?
No. s[1:3] gives positions 1 and 2.
03What does s > 60 return?
A Series of True/False values, which is then used to pick elements.
Variations for the lab test
- Display the last three elements with a negative slice.
- Display students whose marks are between 50 and 80.
- Change Eshan's marks to 60 and display the Series.
! Common mistake Writing
s["Asha", "Divya"] without the inner brackets raises an error; several labels must be given as a list.