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

 

 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

pandas各个excel函数应用:

import pandas as pd
data = pd.read_excel('C:/Users/Administrator/Desktop/test/1.xlsx')

data = data.set_index('名称')
temp = data[['列1','列2']]
data['total'] = temp.sum(axis=1)
data['avg'] = temp.mean(axis=1)
data['max'] = temp.max(axis=1)
data['min'] = temp.min(axis=1)
data['count'] = temp.count(axis=1)
print(data)

列1 列2 total avg max min count
名称
产品1 1 2 3 1.5 2 1 2
产品2 7 3 10 5.0 7 3 2
产品3 5 111 116 58.0 111 5 2

Process finished with exit code 0

 

posted @ 2023-07-31 11:16  往事已成昨天  阅读(34)  评论(0编辑  收藏  举报