Home >Backend Development >Python Tutorial >Python learning 002-pandas VS excel assigns grades to grades

Python learning 002-pandas VS excel assigns grades to grades

fs哆哆
fs哆哆Original
2020-05-09 21:12:26222browse

[Question] There is a score table as follows. Add a column after the total score and enter the grade as follows

Python learning 002-pandas VS excel assigns grades to gradesThe grade is as follows:

# # ScoreLevel90 or aboveA##80-9060-790-59[Knowledge Points]

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】

```python

-*- coding: UTF-8 - *-

import pandas as pd

def get_letter_grade(score):

## if score> ;=90:

Return "A"

elif score>=80:

## return "B"

## elif score>=60:

return "C"

## else:

##                                                                                                                                                                                                       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:

1. Read the Excel results and print them out as

2.d['Grade']=d['Total Score'].apply(lambda x: get_letter_grade (x))

Create a new "level" column and assign the level as follows

Python learning 002-pandas VS excel assigns grades to grades

3.

d.to_excel(' pandas VS excel assigns grades to grades_out.xlsx',index=False)

The output is an excel file with the following contentPython learning 002-pandas VS excel assigns grades to grades

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn