Create bool mask from filter results in Pandas

Learn, how to create bool mask from filter results in Python Pandas? By Pranit Sharma Last updated : October 06, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Boolean masks are of boolean type (obviously) so we can use Boolean operations on them. Boolean operators include & and | which can combine our mask based on either an 'and' operation or an 'or' operation.

Creating a mask to filter dataframe when wearing a single column is simple but we need to create a mask with multiple columns.

Creating bool mask from filter results

In our specific case, we need an 'and' operation so we can simply write our mark, this will ensure that we are selecting those rows for which both conditions are simultaneously satisfied by replacing the 'and' with 'or' one can select those rows for which either of the two conditions can be satisfied.

Let us understand with the help of an example,

Python program to create bool mask from filter results

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a DataFrame
df = pd.DataFrame(data=list(range(10)), columns=['A'])
df['B'] = 'A'
df['B'].loc[5:10] = 'B'

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

# Creating boolean mask
mask = (df['B'] == 'A') & (df['A'] < 4)

# Display result
print("Filtered Data:\n",mask)

Output

The output of the above program is:

Example: Create bool mask from filter results

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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