介绍
在本实验中,你将学习 Pandas 库中的 query() 方法。query() 方法允许你基于布尔表达式过滤 DataFrame。它与 filter() 方法类似。你可以使用此方法基于一个或多个列过滤 DataFrame,并使用 'AND' 运算符组合多个条件。
虚拟机提示
虚拟机启动完成后,点击左上角切换到 Notebook 选项卡以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟,直到 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,请随时向 Labby 寻求帮助。实验结束后提供反馈,我们将及时为你解决问题。
创建 DataFrame
首先,让我们创建一个 DataFrame 来进行操作。在这个例子中,我们将创建一个包含人员信息的 DataFrame,包括他们的姓名、年龄、身高和体重。
#importing pandas as pd
import pandas as pd
#creating the DataFrame
df = pd.DataFrame({'Name': ['Chetan', 'Yashas', 'Yuvraj', 'Pooja', 'Sindu', 'Renuka'],
'Age': [19, 26, 22, 24, 21, 23],
'Height': [165, 150, 168, 157, 155, 170],
'Weight': [60, 65, 70, 50, 52, 55]})
基于单列过滤 DataFrame
接下来,让我们使用 query() 方法基于单列过滤 DataFrame。在这个例子中,我们将过滤 DataFrame,仅包含年龄小于 23 的行。
#filtering the DataFrame by age
filtered_df = df.query('Age < 23')
#printing the filtered DataFrame
print(filtered_df)
输出:
Name Age Height Weight
0 Chetan 19 165 60
2 Yuvraj 22 168 70
4 Sindu 21 155 52
基于两列比较过滤 DataFrame
现在,让我们使用 query() 方法通过比较两列来过滤 DataFrame。在这个例子中,我们将过滤 DataFrame,仅包含 "sci_Marks" 列的值大于 "Maths_Marks" 列值的行。
#creating the DataFrame
df = pd.DataFrame({'Name': ['Chetan', 'Yashas', 'Yuvraj', 'Pooja', 'Sindu', 'Renuka'],
'sci_Marks': [85, 70, 75, 90, 95, 70],
'Maths_Marks': [82, 79, 80, 89, 92, 70]})
#filtering the DataFrame by comparing two columns
filtered_df = df.query('sci_Marks > Maths_Marks')
#printing the filtered DataFrame
print(filtered_df)
输出:
Name sci_Marks Maths_Marks
0 Chetan 85 82
3 Pooja 90 89
4 Sindu 95 92
使用 'AND' 运算符过滤 DataFrame
最后,让我们使用 'AND' 运算符结合多个条件来过滤 DataFrame。在这个例子中,我们将过滤 DataFrame,仅包含身高大于 155 且体重大于 60 的行。
#filtering the DataFrame by using 'AND' operator
filtered_df = df.query('Height > 155 and Weight > 60')
#printing the filtered DataFrame
print(filtered_df)
输出:
Name Age Height Weight
1 Yashas 26 150 65
2 Yuvraj 22 168 70
总结
恭喜你!在这个实验中,你学习了如何在 Pandas 库中使用 query() 方法。你现在已经掌握了如何基于布尔表达式过滤 DataFrame、基于单列过滤、比较两列以及使用 'AND' 运算符结合多个条件。这种方法对于快速高效地过滤 Pandas DataFrame 中的数据非常有用。继续练习并探索不同的用例,以更熟练地使用 query() 方法。