Home >Backend Development >Python Tutorial >Python learning 002-pandas VS excel assigns grades to grades
[Question] There is a score table as follows. Add a column after the total score and enter the grade as follows
The grade is as follows:
A | |
B | |
C | |
D |
apply function
The apply function is the function with the highest degree of freedom among all functions in `pandas`. The function is as follows:
DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)
This function is the most What is useful is the first parameter, which is a function, equivalent to a function pointer in C/C.
This function needs to be implemented by yourself. The incoming parameters of the function are determined according to the axis. For example, if axis = 1, a row of data will be passed to you as the Series data
structure. In the implemented function, we implement the calculation between different attributes of the Series in the function and return a result. The apply function
will automatically traverse the data of each row of DataFrame, and finally combine all the results into one Series data. structure and return.
【Code】## if score> ;=90:
Return "A"
elif score>=80:
## return "B"
## elif score>=60:
return "C"
## Return "D"
d=pd.read_excel('pandas VS excel assigns grades to grades.xlsx')
print(d)
d['Grade']=d['Total Score'].apply(lambda x: get_letter_grade(x) )
print(d)
d.to_excel('pandas VS excel assigns grades to grades_out.xlsx',index=False )
print("done")
```
Process analysis:
2.d['Grade']=d['Total Score'].apply(lambda x: get_letter_grade (x))
Create a new "level" column and assign the level as follows
3.
d.to_excel(' pandas VS excel assigns grades to grades_out.xlsx',index=False)
The output is an excel file with the following content
The above is the detailed content of Python learning 002-pandas VS excel assigns grades to grades. For more information, please follow other related articles on the PHP Chinese website!