Page 28 - Informatics_Practices_Fliipbook_Class12
P. 28
1.5.5 Checking for membership
Pandas allows us to check whether a key is a valid index using the in operator. For example, we could check whether
a roll number appears as an index in markSeries, as illustrated below:
>>> rollNo = 101
>>> print(rollNo in students)
True
>>> print('roll No:', rollNo, 'marks:', students[rollNo])
roll No: 101 marks: 90
>>> rollNo = 104
>>> print('roll No:', rollNo, 'marks:', students[rollNo])
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\
pandas\core\indexes\base.py", line 3653, in get_loc
return self._engine.get_loc(casted_key)
File "pandas\_libs\index.pyx", line 147, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 176, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 2606, in pandas._libs.
hashtable.Int64HashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 2630, in pandas._libs.
hashtable.Int64HashTable.get_item
KeyError: 104
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
print('roll No:', rollNo, 'marks:', students[rollNo])
File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\
pandas\core\series.py", line 1007, in __getitem__
return self._get_value(key)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\
pandas\core\series.py", line 1116, in _get_value
loc = self.index.get_loc(label)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\
pandas\core\indexes\base.py", line 3655, in get_loc
raise KeyError(key) from err
KeyError: 104
Note that above attempt to retrieve marks of the student having roll number 104 resulted in a KeyError because 104
is not a valid key. Instead, we could have checked for the presence of the key 104 in the index before trying to retrieve
the marks for roll number 104, as illustrated below:
>>> rollNo = 104
>>> if rollNo in students:
... print('roll No:', rollNo, 'marks:', students[rollNo])
... else:
... print(rollNo, 'is not a valid index')
output:
104 is not a valid index
>>> rollNo = 106
>>> if rollNo in students:
... print('roll No:', rollNo, 'marks:', students[rollNo])
... else:
... print(rollNo, 'is not a valid index')
output:
roll No: 106 marks: 45
14 Touchpad Informatics Practices-XII

