Python办公自动化|一键生成数据分析报告


前两天逛知乎的时候看到这样一个提问,Python自动化办公能做那些有趣或者有用的事情? 在这里插入图片描述 看了一下这个提问,我想这可能是很多职场人面临的困惑,想把Python用到工作中来提升效率,却不知如何下手?Python在自动化办公领域越来越受欢迎,重复性工作让Python去做将是一种趋势。

看了一些办公自动化的文章,感觉更多是知识的罗列,看完后不知所云。为了更方面大家去学习,今天小编将以学生考试成绩为例, 手把手教你使用Python完成自动化办公,一键生成学生成绩数据分析报告(word版),完整版代码,在下面公众号后台回复:word ,如果对PPT、excel自动化办公感兴趣,可以下方留言。

准备数据

没有数据,数据分析报告无从谈起。 GitHub热榜|5款优质的Python小工具,最后一款真神器! 中介绍过faker可以一行代码实现数据的生成,今天我将使用此方式。

    from faker import Faker
  import pandas as pd
  #生成数据
  fake = Faker('zh_CN')  
  name = []
  sex= []
  score1 = []
  score2 = []
  score3 = []
  score4 = []
  number = range(1,31)
  for _ in range(30):
      name.append(fake.simple_profile(sex=None)['name'])
      sex.append(fake.simple_profile(sex=None)['sex'])
      score1.append(random.randint(40,100))
      score2.append(random.randint(40,100))
      score3.append(random.randint(40,100))
      score4.append(random.randint(200,300))
   
  df = pd.DataFrame({
          '学号':number,
          '姓名':name,    
          '性别':sex,
          '语文':score1,
          '数学':score2,
          '英语':score3,
          '理综':score4
          })
  df = df.set_index('学号')
  df.to_excel('学生成绩单.xlsx')

生成分析报告

考试成绩明细

核心代码

    p = document.add_paragraph('本次测评,全班共有{}名同学参加考试,其中分数总分排名第一的同学是'.format(len(students.姓名)),style='Heading 3')
  p.add_run(str(first_student)).bold = True
  p.add_run(',分数为')
  p.add_run(str(first_score)).bold = True
  p.add_run('.学生考试总体成绩如下')
   
  table = document.add_table(rows=len(students.姓名)+1, cols=6, style='Medium Shading 1 Accent 5')
  table.cell(0,0).text = '姓名'
  table.cell(0,1).text = '语文'
  table.cell(0,2).text = '数学'
  table.cell(0,3).text = '英语'
  table.cell(0,4).text = '理综'
  table.cell(0,5).text = '总分'
   
  for i,(index,row) in enumerate(students.iterrows()):
      table.cell(i+1, 0).text = str(row['姓名'])
      table.cell(i+1, 1).text = str(row['语文'])
      table.cell(i+1, 2).text = str(row['数学'])
      table.cell(i+1, 3).text = str(row['英语'])
      table.cell(i+1, 4).text = str(row['理综'])
      table.cell(i+1, 5).text = str(row['总分'])

结果 在这里插入图片描述

考试成绩汇总

核心代码

    students['总分'] = students.语文 + students.数学 + students.英语 + students.理综
  students.sort_values(by='总分', inplace=True, ascending=False)
  students.reset_index(drop=True, inplace=True)
   
  #学生成绩汇总表
  ax = students.plot.bar(x='姓名', y=['语文','数学','英语','理综'], stacked=True)
  plt.title('学生成绩汇总图', fontsize=16)   # fontproperties=font
  plt.xlabel('姓名', fontsize=10) # fontproperties=font,
  plt.xticks(rotation='45', fontsize=8) # fontproperties=font,
  ax.spines['top'].set_visible(False)
  ax.spines['right'].set_visible(False)
  plt.tight_layout()
  plt.savefig('Part3_data.jpg')

结果展示 在这里插入图片描述

各科成绩表现
    def pie_plot(scores):
      ratios=dict()
      for subject,subjectScore in scores.items():
          ratios[subject]={}
          if subject !='理综':
              for category,num in groupby(sorted(subjectScore),splitScore):
                  ratios[subject][category]= len(tuple(num))
          else:
              for category,num in groupby(sorted(subjectScore),splitScore_lizong):
                  ratios[subject][category]= len(tuple(num))
   
      fig ,axs = plt.subplots(2,2)
      # 画子图
      axs.shape=1,4
      for index,subjectData in enumerate(ratios.items()):
          plt.sca(axs[0][index])
          subjectName,subjectRatio = subjectData
          plt.pie(list(subjectRatio.values()),labels=list(subjectRatio.keys()),autopct='%1.1f%%')
          plt.xlabel(subjectName)
          plt.legend(loc="right",bbox_to_anchor=(1, 0, 0.5, 1))
   
      plt.savefig('Part4_data.jpg')
      plt.show()
  pie_plot(scores)

结果展示 在这里插入图片描述

历次考试成绩

上面都是对一个班级整体的数据分析报告。如果希望一份分析报告中, 除了班级整体成绩分析外,还想生成一份针对个人成绩报告,目的不仅是可以知道这个班级的整体学习状况,也可以知道每个学生的学习情况,下面我们以一个王欢同学为例:

核心代码

    temp_df = pd.DataFrame({
          '历次考试':number,
          '姓名':'王欢',    
          '语文':score1,
          '数学':score2,
          '英语':score3,
          '理综':score4
          })
  plt.subplot(411)
  plt.plot(temp_df['语文'],'y*-',label="语文")
  plt.subplot(412)
  plt.plot(temp_df['数学'],'b*-')
  plt.subplot(413)
  plt.plot(temp_df['英语'],'r*-')
  plt.subplot(414)
  plt.plot(temp_df['理综'])
  plt.savefig('Part6_data.jpg')
  plt.show()

结果展示 在这里插入图片描述

该同学成绩概括性分析

在这里插入图片描述

成果展示

Python自动化办公,目的是提升效率,避免重复劳动,同时可以针对每个人的情况,做到千人千面,省时省力,一键生成,非常简单。因视频不支持,有兴趣的可以公众号上看!

推荐阅读

技术交流

欢迎转载、收藏本文,码字不易,有所收获点赞支持一下!

为方便进行学习交流,本号开通了技术交流群,添加方式如下:

直接添加小助手微信号:pythoner666,备注:CSDN+python,或者按照如下方式添加均可! 在这里插入图片描述

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM