Write a program in Python to print the ‘A’ grade students’ names from a DataFrame

PythonPandasServer Side ProgrammingProgramming

Input

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

Output

And the result for ‘A’ grade students name,

0    stud1
3    stud4
4    stud5

Solution

To solve this, we will follow the below approaches.

  • Define a DataFrame

  • Compare the value to the DataFrame

df[df['Grade']=='A']
  • Store the result in another DataFrame and fetch Name.

Example

Let us see the following implementation to get a better understanding.

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'])

Output

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
raja
Published on 10-Feb-2021 13:35:07
Advertisements