Page 18 - Informatics_Practices_Fliipbook_Class12
P. 18
4 100
dtype: int64
As before, the marks of a student can be accessed using the appropriate index, for example, as demonstrated below:
>>> print(students[2])
95
Oftentimes, it is more convenient to access a student's marks based on their roll number, rather than using the default
integer indexes starting from 0. To do so, we express the roll numbers (corresponding to the marks) in a list or a tuple,
and tell Pandas that the list of roll numbers is to be used for indexing by specifying the name of the list of roll numbers
using the argument index, as shown below:
>>> import pandas as pd
>>> marks = [90.5, 70, 95, 45, 100]
>>> rollNumbers = [101, 102 , 103, 105, 106]
>>> students = pd.Series(marks, index = rollNumbers)
>>> print(students)
output:
101 90.5
102 70.0
103 95.0
105 45.0
106 100.0
dtype: float64
Now, to retrieve the marks of a student with roll number 103, we can use this roll number as the index, as shown below:
>>> print(students[103])
95.0
In a similar manner, we can retrieve the marks of multiple students by providing a list of roll numbers (labels) as the
indexes. For example, marks of students with roll numbers 101, 105, and 106 may be retrieved as follows:
>>> print(students[[101, 105, 106]])
101 90.5
105 45.0
106 100.0
dtype: float64
Pandas provides another mechanism to specify the location of the desired object in a series by specifying the index of
the desired object using the loc attribute, as illustrated below:
>>> # Retrieving an object in a series using the loc attribute
>>> print(students.loc[103])
95.0
While using the suitable indexes such as roll numbers, Pandas still allows us to refer to the objects in a series using
the integer positional indexes by using the attribute iloc instead of loc used for integer(position) based indexing as
shown below:
>>> #Querying a Series based on integer index
>>> print(students.iloc[2])
95.0
However, wherever possible, we prefer using meaningful labels instead of integer labels as indexes for better readability
and interpretability.
Retrieving marks of first three students using slicing with loc and iloc
To retrieve elements from a series, you can specify a range of indexes using a slice in the format start:end:step. By
default, the start and end values correspond to the first and last elements of the series object, respectively. For example,
>>> students.loc[101:103]
output:
101 90.5
102 70.0
103 95.0
4 Touchpad Informatics Practices-XII

