How to apply logical operators for Boolean indexing in Pandas?

Given a Pandas DataFrame, we have to how to apply logical operators for Boolean indexing. By Pranit Sharma Last updated : September 21, 2023

Indexing in Pandas

Index in pandas is just the number of rows defined in a Series or DataFrame. The index always starts from 0 to n-1 where n is the number of rows. The index is used in indexing which is a method of traversing or selecting particular rows and columns or selecting all the rows and columns.

Boolean Indexing

In programming, we sometimes use some specific values that only have two values, either True or False. These values are known as Boolean values. How to apply logical operators for Boolean indexing in Pandas? is nothing but indexing the rows of the pandas DataFrame with their actual values (True or False) rather than naming them with a string or an integer value.

Applying logical operators for Boolean indexing in Pandas

To achieve Boolean indexing, we simply assign a list of Boolean values to the index values while defining a DataFrame.

Note

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example.

Step 1: Create and print a pandas dataframe

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'Name':["Ayushi", "Parth", "Sudhir", "Ganesh"],
    'Post': ["HR", "SDE", "Data-Analyst", "SDE"],
    'Salary':[40000, 50000, 80000, 52000]
}

# Creating a DataFrame
df = pd.DataFrame(d, index = [True, False, True, False])

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

The output of the above program is:

Example 1: Apply logical operators for Boolean indexing

Step 2: Apply logical operators for Boolean indexing

Now we will apply a logical operator in this pandas DataFrame having Boolean indexing.

# Filter all the subsets where salary is 
# greater than 45000
result = df.loc[df['Salary']>45000]

# Display result
print("Employees having salary greater than 45000:\n",result)

The output of the above program is:

Example 2: Apply logical operators for Boolean indexing

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.