Boolean Indexing in Python


The Boolean values like True & false and 1&0 can be used as indexes in panda dataframe. They can help us filter out the required records. In the below exampels we will see different methods that can be used to carry out the Boolean indexing operations.

Creating Boolean Index

Let’s consider a data frame desciribing the data from a game. The various points scored on different days are mentioned in a dictionary. Then we can create an index on the dataframe using True and False as the indexing values. Then we can print the final dataframe.

Example

 Live Demo

import pandas as pd
# dictionary
game = {'Day':["Monday","Tuesday","Wednesday","Thursday","Friday"], 'points':[31,24,16,11,22]}
df = pd.DataFrame(game,index=[True,False,True,False,True])
print(df)

Running the above code gives us the following result

Output

               Day       points
True        Monday           31
False      Tuesday           24
True     Wednesday           16
False     Thursday           11
True        Friday           22

Using .loc[]

This function can be used to filter out records that has a specific Boolean value. In the below example we can see fetch only the records where the Boolean value is True.

Example

 Live Demo

import pandas as pd
# dictionary
game = {'Day':["Monday","Tuesday","Wednesday","Thursday","Friday"], 'points':[31,24,16,11,22]}
df = pd.DataFrame(game,index=[True,False,True,False,True])
#print(df)
print(df.loc[True])

Running the above code gives us the following result

Output

              Day           points
True       Monday       31
True    Wednesday       16
True       Friday       22

Using .ix[]

In this method we also use integers as Boolean values. So we change the True and False values in the dataframe to 1 and 0. Then use them to filter out the records.

Example

 Live Demo

import pandas as pd
# dictionary
game = {'Day':["Monday","Tuesday","Wednesday","Thursday","Friday"], 'points':[31,24,16,11,22]}
df = pd.DataFrame(game,index=[1,1,0,0,1])
#print(df)
print(df.ix[0])

Running the above code gives us the following result:

Output

        Day points
0 Wednesday     16
0 T hursday     11

Updated on: 20-Dec-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements