How to filter rows that meet certain conditions in pandas?
To filter rows that meet certain criteria, you can use boolean indexing. Boolean indexing is a method of selecting rows based on boolean values.
First, create a boolean condition that will return a boolean value for each row of the DataFrame, indicating whether the row meets the condition. Then pass this boolean condition as an index to the DataFrame to filter out the rows that meet the condition.
Here is an example of filtering rows where the ‘Score’ column is greater than or equal to 80.
import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie'],
'Score': [85, 70, 90]})
condition = df['Score'] >= 80
filtered_df = df[condition]
print(filtered_df)
The output is:
Name Score
0 Alice 85
2 Charlie 90
In the example above, a boolean condition was first created as condition = df[‘Score’] >= 80, this condition was then passed as an index to the DataFrame df[condition], resulting in the rows that meet the condition.
You can customize the criteria to filter rows that meet your needs.