Extract pandas DataFrame Rows Conditionally in Python (2 Examples)

In this article, I’ll explain how to get pandas DataFrame rows conditionally in Python.

Preparing the Examples

import pandas as pd                                      # Import pandas library in Python
my_df = pd.DataFrame({'A':range(10, 15),                 # Constructing a pandas DataFrame
                      'B':range(20, 25),
                      'C':range(30, 35)})
print(my_df)
#     A   B   C
# 0  10  20  30
# 1  11  21  31
# 2  12  22  32
# 3  13  23  33
# 4  14  24  34

Example 1: Get Rows Based On Range of Values in pandas DataFrame Column

df1 = my_df.loc[my_df['A'] >= 12]                        # Create subset
print(df1)
#     A   B   C
# 2  12  22  32
# 3  13  23  33
# 4  14  24  34

Example 2: Get Rows Based On Multiple pandas DataFrame Columns

df2 = my_df.loc[(my_df['A'] > 11) & (my_df['B'] <= 23)]  # Create subset
print(df2)
#     A   B   C
# 2  12  22  32
# 3  13  23  33

Further Resources & Related Articles

In addition, you may want to have a look at the other tutorials on this homepage. You can find a selection of posts below.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top