当前位置: 首页 > 后端技术 > Python

用Python玩转Excel:统计函数

时间:2023-03-26 01:06:26 Python

一、统计函数初探这是三门考试的学生报名表。当前的目标是求出总分和平均分。如果您有其他需求,可以参考。importpandasaspddatas=pd.read_excel('students.xlsx',index_col='ID')#分别提取三个结果,更方便数据处理temp=datas[['test1','test2','test3']]#求总分数据s['total']=temp.sum(axis=1)#求平均分数据s['average']=temp.mean(axis=1)#保存到Exceldatas.to_excel('students.xlsx')print(datas)还有很多其他的统计函数,这里只是扔掉,其他的可以参考这个方法,这里注意axis=1表示逐行操作,axis=0表示列-逐列操作,按需选择。如果我想找到所有列的平均值并将其添加到Excel的最后一行,我可以这样做:importpandasaspdimportmatplotlib.pyplotaspltdatas=pd.read_excel('students.xlsx')temp=datas[['test1','test2','test3']]datas['total']=temp.sum(axis=1)datas['average']=temp.mean(axis=1)#求所有的平均值列并添加到Excel的最后一行col_mean=datas[['test1','test2','test3','total','average']].mean(axis=0)datas=datas.append(col_mean,ignore_index=True)数据。to_excel('students.xlsx')print(datas)2.数据去重功能1:过滤掉重复数据使用duplicated函数判断是否有重复,返回一组bool值,TRUE表示重复dupe=dupe[dupe==True]过滤掉重复项,dupe.index重复项索引使用iloc函数datas.iloc[dupe.index]获取重复列功能2:去除重复数据使用drop_duplicates去除重复项,记得设置参数:inplace=Trueimportpandasaspddatas=pd.read_excel('students.xlsx')print('sourcedata:\n',datas)dupe=datas.duplicated(subset='name')dupe=dupe[dupe==True]print('重复数据:\n',datas.iloc[dupe.index])datas.drop_duplicates(subset='name',inplace=True)print('删除重复数据:\n',datas)*****************************************************************************源数据:名称test1test2test3totalaverage0student_00188859126488.0000001student_00359567719264.0000002student_00567647020167.0000003student_00778758123478.0000004student_00950665316956.3333335student_01190878426187.0000006student_01378798123879.3333337student_01576757923076.6666678student_00359567719264.0000009student_00567647020167.00000010student_00778758123478.000000重复数据:nametest1test2test3totalaverage8student_00359567719264.09student_00567647020167.010student_00778758123478.0去重后数据:nametest1test2test3totalaverage0student_00188859126488.0000001student_00359567719264.0000002student_00567647020167.0000003student_00778758123478.0000004student_00950665316956.3333335student_01190878426187.0000006student_01378798123879.3333337student_01576757923076.666667三、旋转数据表前段时间在B在网站上观看《后浪》。视频真的很棒。闲暇之余,我将视频中出现的所有弹幕都抓取下来,去重后保存在上图所示的Excel中。第一行显示字幕,第二行显示视频中字幕出现次数的要求:旋转数据表importpandasaspddatas=pd.read_excel('《后浪》弹幕数据.xlsx')table=datas.transpose()table.to_excel('《后浪》弹幕Thedata.xlsx')其实不难看出pandas中有很多有用的功能。掌握好之后,玩转Excel就非常轻松了。学习Python的路上肯定会遇到困难,不要慌张,我这里有一套学习资料,包括40+电子书,800+教学视频,涉及Python基础、爬虫、框架、数据分析、机学习等等,别怕你学不会!https://shimo.im/docs/JWCghr8...《Python学习资料》关注公众号【蟒圈】,每日优质文章推送。