How to filter data with multiple conditions in pandas?
In Pandas, it is possible to filter data using multiple conditions. You can combine multiple conditions together using logical operators such as & and |.
The following are the steps for filtering data using multiple conditions:
- Set up each condition.
- Combine the conditions using logical operators.
- Filter the data using conditions.
Here is an example:
import pandas as pd
# 创建一个示例数据集
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40],
'Gender': ['Female', 'Male', 'Male', 'Male'],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston']}
df = pd.DataFrame(data)
# 创建条件
condition1 = df['Age'] > 30
condition2 = df['Gender'] == 'Male'
# 使用逻辑运算符将条件组合在一起
combined_condition = condition1 & condition2
# 使用条件筛选数据
filtered_data = df[combined_condition]
print(filtered_data)
Output result:
Name Age Gender City
2 Charlie 35 Male Chicago
3 David 40 Male Houston
In the example above, we first created two conditions (condition1 and condition2), then combined them using the logical operator ‘&’. Finally, we used the combined conditions to filter the data and print the results.