How can pandas extract rows that meet certain condition…
In Pandas, you can use boolean indexing to extract rows that satisfy a certain condition. Boolean indexing is a sequence of boolean values (True/False) that matches the number of rows in the DataFrame, and it can be used to select rows in the DataFrame that meet specific criteria.
Here is an example demonstrating how to use boolean indexing to extract rows that meet a certain condition:
import pandas as pd
# 创建一个示例DataFrame
data = {'Name': ['John', 'Emily', 'Jack', 'Michael'],
'Age': [25, 30, 18, 40],
'City': ['New York', 'Los Angeles', 'Chicago', 'Boston']}
df = pd.DataFrame(data)
# 使用布尔索引提取年龄大于等于30的行
filtered_df = df[df['Age'] >= 30]
print(filtered_df)
Output results:
Name Age City
1 Emily 30 Los Angeles
3 Michael 40 Boston
In the example above, we started by creating a DataFrame, and then used a boolean index df[‘Age’] >= 30 to select rows where the age is greater than or equal to 30. Passing the boolean index as an indexer to the DataFrame will return the rows that meet the condition. Finally, we printed the filtered DataFrame.