AlfonsoPEREZ

StatAA

Jan 28th, 2022 (edited)
661
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from openpyxl import load_workbook
  2. import random
  3.  
  4. wb = load_workbook("200Student Data Set.xlsx")  # Gets workbook
  5. ws = wb.active  # Gets active sheet
  6.  
  7. rows = ws.rows  # Gets rows
  8.  
  9. headers = [cell.value for cell in next(rows)]  # Gets headers
  10.  
  11. # Creates list for males, females, and their respective sample lists.
  12. male_list = []
  13. female_list = []
  14. sample_male_list = []
  15. sample_female_list = []
  16.  
  17. # Extracts rows as a tuple from the workbook to appened to the respective lists
  18. for row in rows:
  19.     dataM = {}
  20.     dataF = {}
  21.     for title, cell in zip(headers, row):
  22.         if row[1].value == "M":  # Checks if corresponding cell in the row contains the value of M
  23.             dataM[title] = cell.value  # appends data to a temporary directory for males
  24.         elif row[1].value == "F":  # Checks if corresponding cell in the row contains the value of F
  25.             dataF[title] = cell.value  # appends data to a temporary directory for females
  26.     male_list.append(dataM)  # Appends the directory to the list
  27.     female_list.append(dataF)  # Appends the directory to the list
  28.  
  29. male_list = [t for t in male_list if t]  # Removes the empty tuples in the list
  30. female_list = [t for t in female_list if t]  # Removes the empty tuples in the list
  31.  
  32. sample_male_list = random.sample(male_list, 30)  # Generates random sample
  33. sample_female_list = random.sample(female_list, 30)  # Generates random sample
  34.  
  35. sample = sample_male_list + sample_female_list
  36.  
  37. print("Sample:", sample) # Outputs
RAW Paste Data Copied