Advertisement
junbjn98

Python - Edited

May 28th, 2018
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.07 KB | None | 0 0
  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3.  
  4. def menu():
  5.     print('+--------- MENU ---------+')
  6.     print('| 1. Import excel file   |')
  7.     print('| 2. Print all data      |')
  8.     print('| 3. Calculation         |')
  9.     print('| 4. Stats               |')
  10.     print('| 5. Update data         |')
  11.     print('| 6. Export excel file   |')
  12.     print('| 7. Print menu          |')
  13.     print('| 8. Exit                |')
  14.     print('+------------------------+')
  15.  
  16.  
  17. def import_file():
  18.     while True:
  19.         try:
  20.             global data
  21.             file_path = input('Enter path: ')
  22.             # print in row
  23.             pd.set_option('expand_frame_repr', False)
  24.             data = pd.read_excel(file_path)
  25.             pd.options.display.max_rows = 100
  26.             pd.options.display.max_columns = 20
  27.             print('Success\n')
  28.             break
  29.         except IOError:
  30.            print ("Error: can\'t find file or read data")
  31.  
  32. def print_data():
  33.     print('\n', data.to_string(index=False), '\n')
  34.  
  35.  
  36. def calculation(score):
  37.     data['Quiz'] = round((data['Quiz 1'] + data['Quiz 2'] + data['Quiz 3']) / 3 + data['Bonus'] - data['Minus'], 1)
  38.     data['GPA'] = round(score[0] * data['Quiz'] + score[1] * data['Midterm'] + score[2] * data['Final'], 1)
  39.     i = 0
  40.     for x in data['GPA']:
  41.         if x >= 90:
  42.             data.loc[i, 'Rank'] = 'A+'
  43.         elif x >= 80:
  44.             data.loc[i, 'Rank'] = 'A'
  45.         elif x >= 70:
  46.             data.loc[i, 'Rank'] = 'B+'
  47.         elif x >= 60:
  48.             data.loc[i, 'Rank'] = 'B'
  49.         elif x >= 50:
  50.             data.loc[i, 'Rank'] = 'C+'
  51.         else:
  52.             data.loc[i, 'Rank'] = 'F'
  53.  
  54.         if x >= 50:
  55.             data.loc[i, 'Status'] = 'Pass'
  56.         else:
  57.             data.loc[i, 'Status'] = 'Fail'
  58.         i += 1
  59.     print('Success\n')
  60.  
  61.  
  62. def stats():
  63.     mean = round(data['GPA'].mean(), 1)
  64.     print('\n* Mean GPA =', mean)
  65.  
  66.     std = round(data['GPA'].std(), 1)
  67.     print('* Stdev GPA =', std)
  68.  
  69.     min_index = data['GPA'].idxmin()
  70.     print('* Min GPA:\n', data.loc[[min_index]].to_string(index=False))
  71.  
  72.     max_index = data['GPA'].idxmax()
  73.     print('* Max GPA:\n', data.loc[[max_index]].to_string(index=False))
  74.  
  75.     c_pass = len(data[data['Status'] == 'Pass'])
  76.     print('* Num pass =', c_pass)
  77.  
  78.     c_fail = len(data[data['Status'] == 'Fail'])
  79.     print('* Num fail =', c_fail, '\n')
  80.  
  81.     # Bar Chart
  82.     # Data
  83.     r = [0, 2, 4, 6, 8, 10]
  84.  
  85.     c_quiz1_50 = len(data[data['Quiz 1'] < 50])
  86.     c_quiz2_50 = len(data[data['Quiz 2'] < 50])
  87.     c_quiz3_50 = len(data[data['Quiz 3'] < 50])
  88.     c_quiz_50 = len(data[data['Quiz'] < 50])
  89.     c_mid_50 = len(data[data['Midterm'] < 50])
  90.     c_final_50 = len(data[data['Final'] < 50])
  91.  
  92.     c_quiz1_50_80 = len(data[data['Quiz 1'] < 80]) - c_quiz1_50
  93.     c_quiz2_50_80 = len(data[data['Quiz 2'] < 80]) - c_quiz2_50
  94.     c_quiz3_50_80 = len(data[data['Quiz 3'] < 80]) - c_quiz3_50
  95.     c_quiz_50_80 = len(data[data['Quiz'] < 80]) - c_quiz_50
  96.     c_mid_50_80 = len(data[data['Midterm'] < 80]) - c_mid_50
  97.     c_final_50_80 = len(data[data['Final'] < 80]) - c_final_50
  98.  
  99.     c_quiz1_80 = len(data[data['Quiz 1'] >= 80])
  100.     c_quiz2_80 = len(data[data['Quiz 2'] >= 80])
  101.     c_quiz3_80 = len(data[data['Quiz 3'] >= 80])
  102.     c_quiz_80 = len(data[data['Quiz'] >= 80])
  103.     c_mid_80 = len(data[data['Midterm'] >= 80])
  104.     c_final_80 = len(data[data['Final'] >= 80])
  105.  
  106.     raw_data = {'greenBars': [c_quiz1_50, c_quiz2_50, c_quiz3_50, c_quiz_50, c_mid_50, c_final_50],
  107.                 'orangeBars': [c_quiz1_50_80, c_quiz2_50_80, c_quiz3_50_80, c_quiz_50_80, c_mid_50_80, c_final_50_80],
  108.                 'blueBars': [c_quiz1_80, c_quiz2_80, c_quiz3_80, c_quiz_80, c_mid_80, c_final_80]}
  109.     df = pd.DataFrame(raw_data)
  110.  
  111.     # From raw value to percentage
  112.     totals = [i + j + k for i, j, k in zip(df['greenBars'], df['orangeBars'], df['blueBars'])]
  113.     greenBars = [i / j * 100 for i, j in zip(df['greenBars'], totals)]
  114.     orangeBars = [i / j * 100 for i, j in zip(df['orangeBars'], totals)]
  115.     blueBars = [i / j * 100 for i, j in zip(df['blueBars'], totals)]
  116.  
  117.     # plot
  118.     barWidth = 0.85
  119.     names = ('Quiz 1', 'Quiz 2', 'Quiz 3', 'Quiz', 'Midterm', 'Final')
  120.     # Create green Bars
  121.     p1 = plt.bar(r, greenBars, color='#b5ffb9', edgecolor='white', width=barWidth)
  122.     # Create orange Bars
  123.     p2 = plt.bar(r, orangeBars, bottom=greenBars, color='#f9bc86', edgecolor='white', width=barWidth)
  124.     # Create blue Bars
  125.     p3 = plt.bar(r, blueBars, bottom=[i + j for i, j in zip(greenBars, orangeBars)], color='#a3acff', edgecolor='white',
  126.                  width=barWidth)
  127.  
  128.     # Custom x axis
  129.     plt.xticks(r, names)
  130.     plt.xlabel("Scores")
  131.     plt.legend((p1[0], p2[0], p3[0]), ('score < 50', '50 <= score < 80 ', 'score >= 80'))
  132.  
  133.     # Box Plot
  134.     plt.subplots(figsize=(5, 5), dpi=88)
  135.     plt.title('Box Plot')
  136.     plt.ylabel('GPA')
  137.     plt.boxplot(data['GPA'])
  138.  
  139.     # Pie Chart
  140.     labels = ['F', 'C+', 'B', 'B+', 'A', 'A+']
  141.     values = [len(data[data['Rank'] == 'F']), len(data[data['Rank'] == 'C+']), len(data[data['Rank'] == 'B']),
  142.               len(data[data['Rank'] == 'B+']), len(data[data['Rank'] == 'A']), len(data[data['Rank'] == 'A+'])]
  143.     fig1, ax1 = plt.subplots(figsize=(5, 5), dpi=88)
  144.     plt.title('Pie Chart')
  145.     ax1.pie(values, labels=labels, autopct='%1.1f%%', startangle=90)
  146.     plt.legend(labels=labels)
  147.  
  148.     plt.show()
  149.  
  150.  
  151. def bar_label(ps):
  152.     for p in ps:
  153.         plt.text(p.get_x() + p.get_width() / 2., p.get_y() + p.get_height() / 2.,
  154.                  '%.1f' % p.get_height() + '%', ha='center', va='center')
  155.        
  156.  
  157. def update_data():
  158.     global score
  159.     while True:
  160.         print()
  161.         # Choose student
  162.         while True:
  163.             i = eval(input('Input No.: '))
  164.             if i > len(data):
  165.                 print('No. out of range.')
  166.             else:
  167.                 print('\n', data.loc[[i - 1]].to_string(index=False))
  168.                 break
  169.  
  170.         # Check whether that is the needed student
  171.         re_print = 0
  172.         while True:
  173.             y = input('Do you want to continue to change the data of this student? (Y/N): ')
  174.             if y != 'Y'and y != 'N':
  175.                 print('Wrong input.')
  176.             elif y == 'Y':
  177.                 list_col = ['Quiz 1', 'Quiz 2', 'Quiz 3', 'Bonus', 'Minus']
  178.                 while True:
  179.                     col_name = input('Input Col name: ')
  180.                     if col_name in list_col:
  181.                         break
  182.                     else:
  183.                         print('The change can only be made for Quiz 1, Quiz 2, Quiz 3, Bonus, Minus.')
  184.  
  185.                 while True:
  186.                     new_value = eval(input('Input new value: '))
  187.                     if new_value < 0 or new_value > 100:
  188.                         print("Wrong input.")
  189.                     else:
  190.                         break
  191.  
  192.                 data.loc[i - 1, col_name] = new_value
  193.                 re_print = 1
  194.                 if len(score) == 3:
  195.                     calculation(score)
  196.             else:
  197.                 if re_print == 1:
  198.                     print('\n', data.loc[[i - 1]].to_string(index=False))
  199.                 break
  200.  
  201.         # Continue to chang data
  202.         while True:
  203.             k = input('Do you want to change anything else? (Y/N): ')
  204.             if k != 'Y' and k != 'N':
  205.                 print('Wrong input.')
  206.             else:
  207.                 break
  208.         if k == 'N':
  209.             print()
  210.             break
  211.  
  212.  
  213. def export_file():
  214.     while True:
  215.         try:
  216.             file_path = input('Enter export path: ')
  217.             data.to_excel(file_path, index=False)
  218.             print('Success\n')
  219.             break
  220.         except ValueError:
  221.             print("Error: invalid input.")
  222.  
  223.  
  224. data = ''
  225. menu()
  226. print("Inport excel file")
  227. import_file()
  228. score = ''
  229. while True:
  230.     try:
  231.         n = eval(input('Input a number: '))
  232.         if n == 1:
  233.             import_file()
  234.         elif n == 2:
  235.             print_data()
  236.         elif n == 3:
  237.             while True:
  238.                 try:
  239.                     score = [float(x) for x in input('Input % [Quiz, Midterm, Final]: ').split(',')]
  240.                     if score[0] + score[1] + score[2] != 1:
  241.                         print("Wrong input.")
  242.                     else:
  243.                         calculation(score)
  244.                         print_data()
  245.                         break
  246.                 except ValueError:
  247.                     print("Error: invalid input.")
  248.                 except IndexError:
  249.                     print("Error: invalid input.")
  250.  
  251.         elif n == 4:
  252.             if len(score) != 3:
  253.                 print("Calculation must be done before Stats.")
  254.             else:
  255.                 stats()
  256.         elif n == 5:
  257.             update_data()
  258.         elif n == 6:
  259.             export_file()
  260.         elif n == 7:
  261.             menu()
  262.         elif n == 8:
  263.             exit()
  264.         else:
  265.             print('Please enter a number between 1 and 8!')
  266.     except NameError:
  267.        print ("Error: invalid input.")
  268.     except SyntaxError:
  269.        print ("Error: invalid input.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement