Boolean indexing is used to filter data through the use of boolean vectors. Boolean vectors are created at the backend with respect to the given condition and all the values against the "true" value are then returned.
Note: It is necessary to use symbols instead of words while working with boolean indexing. We can use
&
,|
, and~
in place ofAND
,OR
, andNOT
.
# import pandasimport pandas as pd# initialize panda seriesser1 = pd.Series([1,2,3,4,5,6])#boolean indexingprint("Orignal Series")print(ser1)print("Example 1: Greater than 2")print(ser1[ser1 > 2])print("Example 2: Less than 5 and greater than 2")print(ser1[(ser1 < 5) & (ser1 > 2)])print("Example 3: Not less than 4")print(ser1[~(ser1 < 4)])
The code given above is an example of boolean indexing in Python, where an array is divided into a sub-array depending on a certain condition.
In the first example, numbers that are greater than 2 are extracted from the series. In the second example, the AND
operator is used to extract values that are greater than 2 and less than 5. Similarly, in the third example, the NOT
operator is used to get the values that are equal to or greater than 4.