用 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进行比较
df[df['Grade']=='A']
将结果存储在另一个DataFrame中并获取Name。
例子
让我们看看下面的实现,以便更好地理解。
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