Skip to content

Write the code to create the series ‘serObj’ and answer the questions that follow.

Write the code to create the series ‘serObj’ and answer the questions that follow.

SOLUTION

Create a Series ……..


import pandas as pd

# create the series
serObj = pd.Series([31, 28, 31, 30], index=['Jan', 'Feb', 'Mar', 'Apr'])
print("Initial series:")
print(serObj)

# i) add one row: 'May' -> 31
serObj['May'] = 31

# ii) update Feb to 29
serObj['Feb'] = 29

# iii) change index to 1,2,3,4,5 in place
serObj.index = [1, 2, 3, 4, 5]

# iv) print a month name having number of days less than 31
# (we'll find all months with days < 31 and show their original names)
# Because we replaced the index with numbers, we'll keep a mapping:
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
mask = serObj < 31
months_with_less_than_31 = [months[i] for i, m in enumerate(mask) if m]
print("Months with days < 31:", months_with_less_than_31)

# v) outputs:
print("serObj < 30 ->")
print(serObj < 30)

print("serObj + 3 ->")
print(serObj + 3)