pandas模块---------------------求和,求平均
求和,求平均
import pandas as pd
student = pd.read_excel('C:/Users/Administrator/Desktop/1.xlsx')
student = student.set_index('ID')
temp = student[['Test_1','Test_2','Test_3']]
student['total'] = temp.sum(axis=1)#axis 0为列 1为行
student['average'] = temp.mean(axis=1)
print(student)
student.to_excel('C:/Users/Administrator/Desktop/2.xlsx')
实现效果:
G:\Python3.8解释器\python.exe C:/Users/Administrator/PycharmProjects/pythonProject/first.py
Name Test_1 Test_2 Test_3 total average
ID
1 Student_001 62 86 83 231 77.000000
2 Student_002 77 97 78 252 84.000000
3 Student_003 57 96 46 199 66.333333
4 Student_004 57 87 80 224 74.666667
5 Student_005 95 59 87 241 80.333333
6 Student_006 56 97 61 214 71.333333
7 Student_007 64 91 67 222 74.000000
Process finished with exit code 0
#######################################
求各科平均值和总和
import pandas as pd
student = pd.read_excel('C:/Users/Administrator/Desktop/2.xlsx')
col_mean = student[["Test_1","Test_2","Test_3","total","average"]].mean()
col_mean["Name"]="Summary"
student = student._append(col_mean,ignore_index=True)
student[["Test_1","Test_2","Test_3","total","average"]] = student[["Test_1","Test_2","Test_3","total","average"]].astype(int)
student.to_excel('C:/Users/Administrator/Desktop/3.xlsx')
print(student)
实现效果如下:
ID Name Test_1 Test_2 Test_3 total average
0 1.0 Student_001 62 86 83 231 77
1 2.0 Student_002 77 97 78 252 84
2 3.0 Student_003 57 96 46 199 66
3 4.0 Student_004 57 87 80 224 74
4 5.0 Student_005 95 59 87 241 80
5 6.0 Student_006 56 97 61 214 71
6 7.0 Student_007 64 91 67 222 74
7 NaN Summary 66 87 71 226 75