Python Dataframe Filter Rows by Condition
To filter rows in a pandas DataFrame based on a condition, you can use boolean indexing. Here’s an example of how to do it:
Get Zeeshan Ali’s stories in your inbox
Join Medium for free to get updates from this writer.
Suppose you have a DataFrame named df with columns 'Column1', 'Column2', and 'Column3', and you want to filter the rows where the values in 'Column2' are greater than 50. Here's how you can do it:
import pandas as pd# Sample DataFrame
data = {
'Column1': [1, 2, 3, 4, 5],
'Column2': [30, 60, 40, 70, 80],
'Column3': ['A', 'B', 'C', 'D', 'E']
}df = pd.DataFrame(data)# Filter rows where 'Column2' is greater than 50
filtered_df = df[df['Column2'] > 50]print(filtered_df)
Output:
Column1 Column2 Column3
1 2 60 B
3 4 70 D
4 5 80 EThe resulting DataFrame filtered_df contains only the rows where the value in 'Column2' is greater than 50.
Make sure you have pandas installed (pip install pandas) if you haven't already. You can run this command in your terminal.






