You are on page 1of 2

Practical 4

DataFrames - Boolean Indexes


Boolean Indexes - Introduction
In boolean indexing, we will select subsets of data based on the actual values of the data
in the DataFrame and not on their row/column labels or integer locations. In boolean
indexing, we use a boolean vector to filter the data. Boolean indexing helps us to select
the data from the DataFrames using a boolean vector. We need a DataFrame with a
boolean index to use the boolean indexing.

AIM
To Create a dataframe with Boolean Indexes
Code #1
import pandas as pd

# Creating Lists

tcode = [101,102,103,104,105]

department = ["IT","ENG","Fine Arts","Fine Arts","ENG"]

rank = ["Lecturer","Reader","Professor","Lecturer","Reader"]

salary = [50000,55000,65000,70000,85000]

gender = ["Male","Female","Female","Male","Male"]

dict_teachers = {"tcode" : tcode,

"department":department,

"rank":rank,

"salary":salary,

"gender":gender

#Creating DataFrame with boolean indexes

df = pd.DataFrame(dict_teachers,index=[True,False,True,False,True])

# Display Full DataFrame

print("The Dataframe is:")

print(df)
# Display those rows having True index

print("Records with True Index:")

print(df.loc[True])

# Display those rows having salary value greater than 70000

print("Staff having salary greater than 70000")

print(df.loc[df["salary"] > 70000])

print("Staff having salary greater than 70000")

print(df[df["salary"] > 70000])

# Display those teachers that belongs to ENG department

print(df.loc[df["department"] == "ENG"] )

# Display those male teachers that belongs to ENG department

#print(df.loc[df["department"] == "ENG" and df["gender"] == "Male"] )

Output
The Dataframe is:
tcode department rank salary gender
True 101 IT Lecturer 50000 Male
False 102 ENG Reader 55000 Female
True 103 Fine Arts Professor 65000 Female
False 104 Fine Arts Lecturer 70000 Male
True 105 ENG Reader 85000 Male
Records with True Index:
tcode department rank salary gender
True 101 IT Lecturer 50000 Male
True 103 Fine Arts Professor 65000 Female
True 105 ENG Reader 85000 Male
Staff having salary greater than 70000
tcode department rank salary gender
True 105 ENG Reader 85000 Male
Staff having salary greater than 70000
tcode department rank salary gender
True 105 ENG Reader 85000 Male
tcode department rank salary gender
False 102 ENG Reader 55000 Female
True 105 ENG Reader 85000 Male

You might also like