使用 Python 编写程序,从 DataFrame 中打印“A”等级学生的姓名。


输入 -

Assume, you have DataFrame,
 Id  Name Grade
0 1 stud1   A
1 2 stud2   B
2 3 stud3   C
3 4 stud4   A
4 5 stud5   A

输出 -

以及“A”等级学生的姓名结果,

0    stud1
3    stud4
4    stud5

解决方案

为了解决这个问题,我们将遵循以下方法。

  • 定义 DataFrame

  • 将值与 DataFrame 进行比较

df[df['Grade']=='A']
  • 将结果存储在另一个 DataFrame 中并获取姓名。

示例

让我们看看以下实现以更好地理解。

import pandas as pd
data =
[[1,'stud1','A'],[2,'stud2','B'],[3,'stud3','C'],[4,'stud4','A'],[5,'stud5','A']]
df = pd.DataFrame(data,columns=('Id','Name','Grade'))
print("DataFrame is\n",df)
print("find the A grade students name\n")
result = df[df['Grade']=='A']
print(result['Name'])

输出

DataFrame is
 Id Name Grade
0 1 stud1  A
1 2 stud2  B
2 3 stud3  C
3 4 stud4  A
4 5 stud5  A
find the A grade students name
0    stud1
3    stud4
4    stud5
Name: Name, dtype: object

更新于: 2021年2月24日

566 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.