Page 25 - Informatics_Practices_Fliipbook_Class12
P. 25
>>> for item in sections:
... classStrength += item
>>> print("Total Strength:", classStrength)
output:
Total Strength: 340
While the above code is simple enough, Pandas provides several useful methods such as sum() that can be used to
get the results effortlessly. The method sum(), sums up all values in a series, as demonstrated below:
>>> sections.sum()
output:
340
Similarly, to find the minimum and maximum sanctioned section strengh, we can use the methods min() and max(),
respectively, as shown below:
>>> sections.min(), sections.max()
output:
(35, 60)
Next, suppose, we also need to know which section has the maximum strength. Pandas method idxmax() yields the
index of the maximum value in the series. For example,
>>> sections.idxmax(), sections.max()
output:
('C', 60)
Similarly, Pandas method idxmin() yields the index of the minimum value in the series.
For example,
>>> sections.idxmin(), sections.min()
output:
('A', 35)
Next, suppose, the school decides to increase the sanctioned strength of each section by 5. This requires adding 5 to
each value of the series sections. Pandas allow arithmetic operators to be applied to each element of the series as
illustrated below:
>>> sections = sections + 5
>>> print(sections)
output:
A 40
B 55
C 65
D 60
E 50
F 45
G 60
dtype: int64
You may be wondering that while sections is series, 5 is a scalar, so how can we apply the + operator? Indeed,
Pandas expands 5 to form an object of a compatible type, so that the + operator can be applied elementwise. This
transformation of a scalar quantity to an object compatible with the series sections quantity is called broadcasting.
In fact, broadcasting is a general term that transforms an object of lower dimension into an object of a higher dimension.
Thus, an integer may be expanded to a vector or a matrix.
>>> import pandas as pd
>>> sectionNamesXI = ['A','B','C','D','E','F','G']
>>> sectionStrengthXI = [40, 50, 50, 50, 40, 60, 50]
>>> sections = pd.Series(sectionStrengthXI, index = sectionNamesXI)
Data Handling using Pandas 11

