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 |
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 |
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 |
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 |
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.