Q. Write a program to iterate over a data-frame containing names and marks, which then calculates grades as per marks (as per guidelines below) and adds them to the grade column.
Marks >= 90 grade A+;
Marks 70-90 grade A;
Marks 68-70 grade B;
Marks 50-60 grade C;
Marks 40-50 grade D;
Marks < 40 grade F
Answer :-
import pandas as pd import numpy as np names = pd.Series (['Path', 'Walla', 'Computer', 'Portal', 'Express']) marks = pd. Series ([61, 75.0, 95, 89, 73.6]) Stud = { 'Name': names, 'Marks': marks } df1 = pd.DataFrame (Stud, columns = ['Name', 'Marks']) df1['Grade'] = np.NaN print ("Initial values in dataframe") print (df1) for (col, colSeries) in df1.iteritems(): length = len(colSeries) if col == 'Marks': lstMrks = [] for row in range (length) : mrks = colSeries [row] if mrks >= 90 : lstMrks.append('A+') elif mrks >= 70 : lstMrks.append('A') elif mrks >= 60 : lstMrks.append('B') elif mrks >= 50 : lstMrks.append('C') elif mrks >= 40: lstMrks.append('D') else: lstMrks.append('F') df1['Grade'] = lstMrks print("\n Dataframe after calculating grades") print (df1)
Output :-
Initial values in dataframe
Name Marks Grade
0 Path 61.0 NaN
1 Walla 75.0 NaN
2 Computer 95.0 NaN
3 Portal 89.0 NaN
4 Express 73.6 NaN
Dataframe after calculating grades
Name Marks Grade
0 Path 61.0 B
1 Walla 75.0 A
2 Computer 95.0 A+
3 Portal 89.0 A
4 Express 73.6 A
>>>
Post a Comment
You can help us by Clicking on ads. ^_^
Please do not send spam comment : )