How to filter a DataFrame using one conditional statement

0 min

You can filter a DataFrame by applying a mask.

Here is how

We define a sample DataFrame

import pandas as pd

# We read a sample dataset from the web.
df = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
We read our sample dataset

One conditional statement mask

A condition within squared brackets

# The mask
mask = df["sepal_length"] > .4

# We apply the mask
print(df[mask])
Defining a conditional statement as a mask

it is also possible to it in one-line

print(df[df["sepal_length"] > .4])
Directly within the squared brackets

You might also be interested in how to apply multiple conditional statements.