def parse_response(resp: str): html_parser = bs(resp.text, "html.parser") all_tables = html_parser.findAll("table") general_details = all_tables[2] physical_appearance = all_tables[3] personality = all_tables[4] federal_taxpayer_id_nums = all_tables[5] general_details_tbl = PT() general_details_tbl.field_names = [ "%sGeneral Details%s" % (fg(randint(1, 220)), attr(0)), "%sValues%s" % (fg(randint(1, 220)), attr(0)) ] for row in general_details.findAll("tr"): v = extract_row_data_cells(str(row)) if len(v) != 2: continue else: general_details_tbl.add_row(v) print(general_details_tbl) physical_appearance_tbl = PT() physical_appearance_tbl.field_names = [ "%sPhysical Appearance%s" % (fg(randint(1, 220)), attr(0)), "%sValues%s" % (fg(randint(1, 220)), attr(0)) ] for row in physical_appearance.findAll("tr"): v = extract_row_data_cells(str(row)) if len(v) != 2: continue else: physical_appearance_tbl.add_row(v) print(physical_appearance_tbl) personality_tbl = PT() personality_tbl.field_names = [ "%sPersonality Traits%s" % (fg(randint(1, 220)), attr(0)), "%sValues%s" % (fg(randint(1, 220)), attr(0)) ] for row in personality.findAll("tr"): v = extract_row_data_cells(str(row)) if len(v) != 2: continue else: personality_tbl.add_row(v) print(personality_tbl) federal_taxpayer_tbl = PT() federal_taxpayer_tbl.field_names = [ "%sUS Federal Taxpayer Id Number (Tin)%s" % (fg(randint(1, 220)), attr(0)), "%sTax ID%s" % (fg(randint(1, 220)), attr(0)) ] for row in federal_taxpayer_id_nums.findAll("tr"): v = extract_row_data_cells(str(row)) if len(v) != 2: continue else: federal_taxpayer_tbl.add_row(v) print(federal_taxpayer_tbl)
def middle(self): """ to print out the results for the metadata files that failed the tests :return: :rtype: """ self.m_files = self.m_passing = len(self.results.values()) if self.console and self.verbose > 0: print('', flush=True) if False not in [unit.status for unit in self.results.values()]: print('All Metadata Files Passed', flush=True) else: display_table = PT(["Filename", "Failed Tests"]) display_table.align["Filename", "Failed Tests"] = 'c' display_table.hrules = pt_all for unit in sorted(self.report['units'], key=lambda x: x['name']): if unit['status'] is not True: self.m_passing -= 1 display_table.add_row([ unit['name'], '\n'.join([ '{test} failed'.format(test=x) for x in unit['units'] if unit['units'][x] is False ]) ]) print(display_table, flush=True)
def analysis(): try: file3 = open('pattern.txt', 'rb') except: print '\nNo Data found!\n' return table = PT(['S.no', 'College', 'Course']) i = 1 try: while True: obj3 = pickle.load(file3) table.add_row([i, obj3.college, obj3.course]) i += 1 except EOFError: print table file3.seek(0) ch = int(raw_input("Select your choice (0 for none) : ")) #GO for Loop os.system(clean) if ch: for i in range(ch): obj5 = pickle.load(file3) else: print '\n\t', obj5.college, ' -- ', obj5.course, '\n' obj5.tabular() else: return 1
def conteststatus(res): res = res['result'] s = [] for r in res: s.append(Submission(r)) pt = PT() pt.junction_char = '.' pt.padding_width = 0 fn = [ "handle", "Participant Type", "Problem ID", "Problem Name", "Points", "Language", "Verdict", "TestSet", "Passed Tests", "Time(ms)", "Memory(bytes)" ] for i in range(len(fn)): fn[i] = get_colored(fn[i], 'magenta') pt.field_names = fn for i in s: hand = i.author.members[0].handle ptype = i.author.participantType pid = str(i.problem.contestId) + str(i.problem.index) pname = i.problem.name points = str(i.problem.points) lang = i.programmingLanguage verd = i.verdict ts = i.testset ptest = str(i.passedTestCount) time = str(i.timeConsumedMillis) mem = str(i.memoryConsumedBytes) lis = [ hand, ptype, pid, pname, points, lang, verd, ts, ptest, time, mem ] for j in range(len(lis)): lis[j] = get_colored(lis[j], 'cyan') pt.add_row(lis) pydoc.pager(pt.get_string())
def convert_csv_table_to_html(table_csv): table_headers = table_csv[0].split(';') table_html = PT(table_headers) for row_index in range(1, len(table_csv)): curr_row = table_csv[row_index].split(';')[:-1] table_html.add_row(curr_row) return table_html
def userstatus(res): res = res['result'] s = [] for r in res: s.append(Submission(r)) pt = PT() fn = ["Problem ID", "Problem Name", "Points","Language", "Verdict", "TestSet", "Passed Tests", "Time(ms)", "Memory(bytes)"] for i in range(len(fn)): fn[i] = get_colored(fn[i], 'magenta') pt.field_names = fn for i in s: pid = str(i.problem.contestId)+str(i.problem.index) pname = i.problem.name points = str(i.problem.points) lang = i.programmingLanguage verd = i.verdict ts = i.testset ptest = str(i.passedTestCount) time = str(i.timeConsumedMillis) mem = str(i.memoryConsumedBytes) lis = [pid,pname,points,lang,verd,ts,ptest,time,mem] for j in range(len(lis)): lis[j] = get_colored(lis[j], 'cyan') pt.add_row(lis) pydoc.pager(pt.get_string())
def show_projs(self): proj_table = PT() proj_table.field_names = ['id', 'uid', 'proj name', 'repo type'] for i in range(len(self.projs)): proj_obj = self.projs[self.index[i+1]] proj_table.add_row([i+1, self.index[i+1], proj_obj['name'], proj_obj['rep_type']]) print(proj_table)
def print_fenshu(fenshu): t = PT(['序号', '名称', '类型', '学分', '成绩']) i = 1 for item in fenshu: t.add_row( [i, item['name'], item['type'], item['point'], item['grade']]) i = i + 1 print(t)
def pt_table(fields, items): """ Prints the data in tabular from. """ table = PT(fields, header_style='upper') for i in items: table.add_row(i) print(table)
def simpson(a, b, errors): table = PT() table.title = "Numerical Approximation for Integration using Simpson Rule" table.field_names = ["Error", "N", "Approximation M=" + str(M(a, b))] for e in errors: s, n = simpsonRule(a, b, e + 1) table.add_row([str(error(e + 1)), str(n), str(dm.Decimal(s))]) print(table) print("\n" * 3)
def major_table(self): """Get pretty table as output of majors""" print() print("Major Summary:") header = ['Dept', 'Required', 'Elective'] x = PT(header) for key in self.majors.keys(): x.add_row([key, sorted(self.majors[key].required_courses), sorted(self.majors[key].elective_courses)]) print(x) return None
def ConfuseMatrix(self, reallist, prelist): ''' :param reallist: 真实的类别列表 :param prelist: 预测的类别列表 :return: 输出混淆矩阵 ''' zidian = self.Tom(reallist, prelist) lieming = sorted(zidian.keys()) table = PT(['混淆矩阵'] + ['预测%s' % d for d in lieming]) for jj in lieming: table.add_row(['实际%s' % jj] + [zidian[jj][kk] for kk in lieming]) return table
def tabular(self): table = PT(['Round', 'Year', 'OpeningRank', 'ClosingRank']) empty = [' '] * 4 for i in range(7): table.add_row([i + 1, 2017] + self.state[i][0]) if i < self.currentRound: table.add_row([i + 1, 2018] + self.state[i][1]) table.add_row(empty) print table
def student_table(self): """Get pretty table as output for students""" print() print("Student Summary:") header = ["CWID", "Name", "Major", "Courses Completed Satisfactorily", "Remaining Required", "Remaining Electives"] x = PT(header) for item in self.students.keys(): # First get difference between required and completed classes passed satisfactorily (grade >= 'C') passed_courses, required_remaining, elective_remaining = self.courses_remaining(item) x.add_row([str(self.students[item].CWID), str(self.students[item].name), str(self.students[item].major), sorted(passed_courses), sorted(required_remaining), sorted(elective_remaining)]) print(x) return None
def instructor_table(self): """Get pretty table as output for instructors""" print() print("Instructor Summary:") # decided to display 'Dept' as well, though not required by assignment header = ["CWID", "Name", "Dept", "Course", "Students"] x = PT(header) for item in self.instructors.keys(): class_list = list(self.instructors[item].courses.keys()) for subject in class_list: x.add_row([str(self.instructors[item].CWID), str(self.instructors[item].name), str(self.instructors[item].dept), subject, self.instructors[item].courses[subject]]) print(x) return None
def print_db(): cursor.execute('''SELECT * FROM humans ;''') result = cursor.fetchall() print() table = PT() table.field_names = ['ID', 'First_name', 'Last_name', 'Birthday', 'Age'] if len(result) == 0: print('\n', 'Сдесь пока никого нет, но скоро сдесь будут люди', '\n') print(table) else: for man in result: table.add_row(man) print(table.get_string(sortby="Age", reversesort=True, align='c'))
def rectangle(a, b, k, d=True): #if d is true,it will show the graph of approximation for every k m = M(a, b, simpson=False) #m calculation~ table = PT() table.title = "Numerical Approximation for Integration using Rectangles" table.field_names = ["N", "Approximation M=" + str(m), "Error"] for i in range(1, k + 1): s, e = rectangleRule(a, b, 2**i, m, d) er = '%.2E' % dm.Decimal(str(e)) table.add_row([str(2**i), str(dm.Decimal(s)), er]) print(table) print("\n" * 3)
def student_table(self): """Get pretty table as output for students""" # 'Registered' instead of 'Completed' as may not have grades for all classes yet print() print("Student Summary:") header = ["CWID", "Name", "Major", "Registered Courses"] x = PT(header) for item in self.students: x.add_row([ str(item.CWID), str(item.name), str(item.major), sorted(list(item.courses.keys())) ]) print(x) return None
def pearsonCorrel(data, printSig, *measures): '''This function computes the Pearson correlation over all the possible pairs of the variables included. INPUT: data is the dictionary containing the data names and values (dict). printSig is a boolean variable, True: the function only prints the significative results, False: the function prints all the values (bool). *measures contain all the variables to compare (strings). OUTPUT: The function prints a table in the terminal containing all the tests computed.''' if not isinstance(data, dict): print( 'Error: data must be a dict. Use dataRead function to import your excel data.' ) else: if not isinstance(printSig, bool): print( 'Error: printSig must be a bool. True: the function only prints the siginificative results/ False: ' 'the function prints all the results.') else: if not len(measures) >= 2: print( 'Error: At least two measures are necessary to compute correlation.' ) else: pairs = list(itertools.combinations(measures, 2)) results = OrderedDict() for i in range(len(pairs)): testName = pairs[i][0] + '/' + pairs[i][1] res = stats.pearsonr(data[pairs[i][0]], data[pairs[i][1]]) results[testName] = res table_matrix = [[ 'Pearson correlation', 'Correl. coefficient', 'p-Value' ]] if printSig: m = results.keys() for k in range(len(m)): pVal = results[m[k]][1] if pVal < 0.05: table_matrix.append( [m[k], results[m[k]][0], results[m[k]][1]]) else: m = results.keys() for k in range(len(m)): table_matrix.append( [m[k], results[m[k]][0], results[m[k]][1]]) table = PT(table_matrix[0]) for row in range(1, len(table_matrix)): table.add_row(table_matrix[row]) print table return table_matrix
def ConfuseMatrix(reallist, prelist, dcix=data.exdixxt): ''' :param reallist: 真实的类别列表 :param prelist: 预测的类别列表 :return: 输出混淆矩阵 ''' # 首先将字典的键值互换 ruid = {} for jj in dcix: ruid[dcix[jj]] = jj zidian = Tom(reallist, prelist) lieming = sorted(zidian.keys()) table = PT(['混淆矩阵'] + ['预测%s' % ruid[d] for d in lieming]) for jj in lieming: table.add_row(['实际%s' % ruid[jj]] + [zidian[jj][kk] for kk in lieming]) return table
def pairedTtest(data, printSig, *measures): '''This function computes the paired T-test for pairs of measures from data dictionary. INPUT: data is the dictionary containing the data names and values (dict). printSig is a boolean variable, True: the function only prints the significative results, False: the function prints all the values (bool). *measures contain all the pairs of variables to compare (strings). OUTPUT: The function prints a table in the terminal containing all the tests computed.''' if not isinstance(data, dict): print( 'Error: data must be a dict. Use dataRead function to import your excel data.' ) else: if not isinstance(printSig, bool): print( 'Error: printSig must be a bool. True: the function only prints the siginificative results/ False: ' 'the function prints all the results.') else: if len(measures) % 2 == 0: results = OrderedDict() for i in range(0, len(measures), 2): testName = measures[i] + '/' + measures[i + 1] res = stats.ttest_rel(data[measures[i]], data[measures[i + 1]]) results[testName] = res table_matrix = [['Paired T-test', 'Test Statistic', 'p-Value']] if printSig: m = results.keys() for k in range(len(m)): pVal = results[m[k]][1] if pVal < 0.05: table_matrix.append( [m[k], results[m[k]][0], results[m[k]][1]]) else: m = results.keys() for k in range(len(m)): table_matrix.append( [m[k], results[m[k]][0], results[m[k]][1]]) table = PT(table_matrix[0]) for row in range(1, len(table_matrix)): table.add_row(table_matrix[row]) print table else: print('Error: Measures must be paired two by two') return table_matrix
def normalityTest(data, printSig, *measures): '''This function computes the normality test for the variables included. INPUT: data is the dictionary containing the data names and values (dict). printSig is a boolean variable, True: the function only prints the significative results, False: the function prints all the values (bool). *measures contain all the variables to compute the test over (strings). OUTPUT: The function prints a table in the terminal containing all the tests computed.''' if not isinstance(data, dict): print( 'Error: data must be a dict. Use dataRead function to import your excel data.' ) else: if not isinstance(printSig, bool): print( 'Error: printSig must be a bool. True: the function only prints the siginificative results/ False: ' 'the function prints all the results.') else: results = OrderedDict() for i in range(len(measures)): testName = measures[i] res = stats.normaltest(data[measures[i]]) results[testName] = res table_matrix = [['Normality test', 'Test Statistic', 'p-Value']] if printSig: m = results.keys() for k in range(len(m)): pVal = results[m[k]][1] if pVal < 0.05: table_matrix.append( [m[k], results[m[k]][0], results[m[k]][1]]) else: m = results.keys() for k in range(len(m)): table_matrix.append( [m[k], results[m[k]][0], results[m[k]][1]]) table = PT(table_matrix[0]) for row in range(1, len(table_matrix)): table.add_row(table_matrix[row]) print table return table_matrix
def print_board(self): """Function to print out a pretty table of the game board.""" print() print("Tic Tac Toe Game Board:") header = list() count = 0 for column in range(self.size): count += 1 header.append(str(count)) header = ["Row/Column"] + header z = PT(header) for x in range(self.size): z_list = list() for y in range(self.size): z_list.append(self.board[x][y]) z_list = [str(x + 1)] + z_list # print(z_list, type(z_list)) z.add_row(z_list) # print(z.get_string()) print() print("Pretty Table:") print(z) return None
async def rolestats(self, ctx): """get simple stats on all roles in server""" roles = ctx.guild.roles role_groups = separate(roles, 30) for i, rg in enumerate(role_groups): pt = PT() pt.field_names = ["role", "members", "%"] # add field names for rows pt.align = "l" # left align PrettyTable embed = discord.Embed() for role in rg: name = role.name[:15] + ("..." if len(role.name) > 15 else "" ) # keep role name < 15 chars members = len(role.members) # get role member count percentage = len(role.members) / len( ctx.guild.members ) * 100 # get members:server members ratio pt.add_row([name, members, f"{(percentage):.2f}"]) # add to PT if i == 0: embed.title = "Role stats" embed.description = f"```\n{pt}\n```" await ctx.send(embed=embed) await asyncio.sleep(0.51)
def conf(self): conf_choices = { '1': 'Add node', '2': 'Del node', '3': 'Back to home', '0': 'Exit' } os.system('clear') print(''.center(ROW_NUM, '-')) print('Cluster node infos ...') print(''.center(ROW_NUM, '=')) node_table = PT() node_table.field_names = [ "hostname", "ip(x.x.x.x/y)", "NIC", "node type" ] nodes = NodeHandler().get() for k, v in nodes.items(): node_table.add_row([ v['hostname'], '{}/{}'.format(k, v['netmask']), v['nic'], v['node_role'] ]) print(node_table) for k, v in conf_choices.items(): print('> {}: {}'.format(k, v)) print(''.center(ROW_NUM, '-')) choice = input('>> ') if choice == '0': sys.exit() elif choice == '3': self.home() else: self.conf()
import subprocess import prettytable from prettytable import PrettyTable as PT import sys from colorama import init, Fore, Back #cmd = "wget http://fanyi.badu.com/v2transapi?query=hello | python -m json.tool" cmd = "php {} | python -m json.tool".format(sys.argv[1]) p = subprocess.Popen( ["php test.php | python -m json.tool", "python -m json.tool"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) result = "" while True: data = p.stdout.readline() if data == b'': break else: result += data.decode('ascii').encode('utf8').decode('utf8') table = PT(["文件名称", "执行结果"]) init(autoreset=True) filename = Fore.YELLOW + sys.argv[1] + '' table.add_row([filename, Fore.GREEN + result]) table.align = 'l' print table
def repMeasBonferroniCorrect(data, printSig, *measures): '''This function computes the Bonferroni correction for pairwise combination of measures from data dictionary. INPUT: data is the dictionary containing the data names and values (dict). printSig is a boolean variable, True: the function only prints the significative results, False: the function prints all the values (bool). *measures contain all the variables to compute the pairwise tests (strings). OUTPUT: The function prints a table in the terminal containing all the tests computed.''' if not isinstance(data, dict): print( 'Error: data must be a dict. Use dataRead function to import your excel data.' ) else: if not isinstance(printSig, bool): print( 'Error: printSig must be a bool. True: the function only prints the siginificative results/ False: ' 'the function prints all the results.') else: n = len(measures) results = OrderedDict() for i in range(0, len(measures)): results[measures[i]] = [] for j in range(0, len(measures)): if j != i: res = stats.ttest_rel(data[measures[i]], data[measures[j]]) results[measures[i]].append([measures[j], res]) table_matrix = [[ 'Bonferroni correction', 'Pairwise T-test', 'Test Statistic', 'p-Value' ]] if printSig: m = results.keys() for k in range(len(m)): count = 0 for t in range(len(results[m[k]])): pVal = results[m[k]][t][1][1] if pVal < (0.05 / n): count = count + 1 if count == 1: table_matrix.append([ m[k], results[m[k]][t][0], results[m[k]][t][1][0], results[m[k]][t][1][1] ]) else: table_matrix.append([ '', results[m[k]][t][0], results[m[k]][t][1][0], results[m[k]][t][1][1] ]) table_matrix.append( ['Sig if p-Value < ' + str(0.05 / n), '-', '--', '---']) else: m = results.keys() for k in range(len(m)): for t in range(len(results[m[k]])): if t == 0: table_matrix.append([ m[k], results[m[k]][t][0], results[m[k]][t][1][0], results[m[k]][t][1][1] ]) else: table_matrix.append([ '', results[m[k]][t][0], results[m[k]][t][1][0], results[m[k]][t][1][1] ]) table_matrix.append( ['Sig if p-Value < ' + str(0.05 / n), '-', '--', '---']) table = PT(table_matrix[0]) for row in range(1, len(table_matrix)): table.add_row(table_matrix[row]) print table return table_matrix
def repeatedMeasuresAnova(data, subID, conditionName, *measures): '''This function computes a ANOVA for repeated measures over the variables defined along with the condition factor. INPUT: data is the dictionary containing the data names and values (dict). subID is the name of the variable that codes the identifier of the subjects(string). conditionName is the name of the condition over you want to compute the ANOVA (string). *measures contain pairs of variable / condition over you want to compute the ANOVA. OUTPUT: The function prints a table in the terminal containing all the tests computed.''' if not isinstance(data, dict): print( 'Error: data must be a dict. Use dataRead function to import your excel data.' ) else: if not isinstance(subID, basestring): print( 'Error: subID must be a string containing the name of the variable with the subjects ID.' ) else: if not isinstance(conditionName, basestring): print( 'Error: conditionName must be a string containing the name of the condition analyzed in the' ' anova.') else: errorCount = 0 for elem in range(len(measures)): if not isinstance(measures[elem], tuple): errorCount = errorCount + 1 if errorCount != 0: print( 'Error: measures must contain tuples with a data variable and an associated condition.' ) else: Sub = namedtuple('Sub', ['Sub_id', 'measure', 'condition']) df = pt.DataFrame() for i in range(len(measures)): meas = data[measures[i][0]] for j in range(len(meas)): df.insert( Sub(data[subID][j], meas[j], measures[i][1])._asdict()) aov = df.anova('measure', sub='Sub_id', wfactors=['condition']) table_matrix = [ ['Source', '', 'Type III SS', 'df', 'SM', 'F', '.Sig'], [ conditionName, 'Sphericity Assumed', aov[('condition', )]['ss'], aov[('condition', )]['df'], aov[('condition', )]['mss'], aov[('condition', )]['F'], aov[('condition', )]['p'] ], [ '', 'Greenhouse-Geiser', aov[('condition', )]['ss'], aov[('condition', )]['df_gg'], aov[('condition', )]['mss_gg'], aov[('condition', )]['F_gg'], aov[('condition', )]['p_gg'] ], [ '', 'Hyunh-Feldt', aov[('condition', )]['ss'], aov[('condition', )]['df_hf'], aov[('condition', )]['mss_hf'], aov[('condition', )]['F_hf'], aov[('condition', )]['p_hf'] ], [ '', 'Box', aov[('condition', )]['ss'], aov[('condition', )]['df_lb'], aov[('condition', )]['mss_lb'], aov[('condition', )]['F_lb'], aov[('condition', )]['p_lb'] ], [ 'Error(' + conditionName + ')', 'Sphericity Assumed', aov[('condition', )]['sse'], aov[('condition', )]['dfe'], aov[('condition', )]['mse'], '-', '--' ], [ '', 'Greenhouse-Geiser', aov[('condition', )]['sse'], aov[('condition', )]['dfe_gg'], aov[('condition', )]['mse_gg'], '-', '--' ], [ '', 'Hyunh-Feldt', aov[('condition', )]['sse'], aov[('condition', )]['dfe_hf'], aov[('condition', )]['mse_hf'], '-', '--' ], [ '', 'Box', aov[('condition', )]['sse'], aov[('condition', )]['dfe_lb'], aov[('condition', )]['mse_lb'], '-', '--' ] ] table = PT(table_matrix[0]) for row in range(1, len(table_matrix)): table.add_row(table_matrix[row]) print table return table_matrix
def groupedIndepTtest(data, sortBy, printSig, groupBy, *measures): '''This function computes the paired T-test for pairs of measures from data dictionary. INPUT: data is the dictionary containing the data names and values (dict). printSig is a boolean variable, True: the function only prints the significative results, False: the function prints all the values (bool). *measures contain all the pairs of variables to compare (strings). OUTPUT: The function prints a table in the terminal containing all the tests computed.''' sortedData = analyzeBy(data, sortBy) if not isinstance(printSig, bool): print( 'Error: printSig must be a bool. True: the function only prints the siginificative results/ False: ' 'the function prints all the results.') else: if not isinstance(groupBy, list) and len(groupBy) == 3: print( 'Error: groupBy must be a list with three elements, the first one is the variable of grouping,' ' the second and the third are the groups to compare.') else: fullResults = OrderedDict() for i in range(len(sortedData.keys())): groupName = sortedData.keys()[i] tempData = sortedData[sortedData.keys()[i]] indexG1 = [] indexG2 = [] results = OrderedDict() for j in range(len(tempData[groupBy[0]])): if tempData[groupBy[0]][j] == groupBy[1]: indexG1.append(j) elif tempData[groupBy[0]][j] == groupBy[2]: indexG2.append(j) for j in range(len(measures)): m1 = [] m2 = [] for g1 in range(len(indexG1)): m1.append(tempData[measures[j]][g1]) for g2 in range(len(indexG2)): m2.append(tempData[measures[j]][g2]) levene = stats.levene(m1, m2) if levene[1] > 0.05: testName = measures[j] + ' (' + groupBy[ 1] + '/' + groupBy[2] + ')' res = stats.ttest_ind(m1, m2, equal_var=True) results[testName] = [levene, res] elif levene[1] < 0.05: testName = measures[j] + ' (' + groupBy[ 1] + '/' + groupBy[2] + ')' res = stats.ttest_ind(m1, m2, equal_var=False) results[testName] = [levene, res] fullResults[groupName] = results table_matrix = [[ '', 'Independent T-test', 'Levene Statistic', 'Levene p-Value', 'Test Statistic', 'p-Value' ]] for i in range(len(fullResults.keys())): if printSig: results = fullResults[fullResults.keys()[i]] m = results.keys() for k in range(len(m)): pVal = results[m[k]][1][1] if pVal < 0.05: if k == 0: table_matrix.append([ fullResults.keys()[i], m[k], results[m[k]][0][0], results[m[k]][0][1], results[m[k]][1][0], results[m[k]][1][1] ]) else: table_matrix.append([ '', m[k], results[m[k]][0][0], results[m[k]][0][1], results[m[k]][1][0], results[m[k]][1][1] ]) else: results = fullResults[fullResults.keys()[i]] m = results.keys() for k in range(len(m)): if k == 0: table_matrix.append([ fullResults.keys()[i], m[k], results[m[k]][0][0], results[m[k]][0][1], results[m[k]][1][0], results[m[k]][1][1] ]) else: table_matrix.append([ '', m[k], results[m[k]][0][0], results[m[k]][0][1], results[m[k]][1][0], results[m[k]][1][1] ]) table = PT(table_matrix[0]) for row in range(1, len(table_matrix)): table.add_row(table_matrix[row]) print table return table_matrix
def groupedPairedTtest(data, sortBy, printSig, *measures): '''This function computes the paired T-test for pairs of measures from data dictionary. INPUT: data is the dictionary containing the data names and values (dict). printSig is a boolean variable, True: the function only prints the significative results, False: the function prints all the values (bool). *measures contain all the pairs of variables to compare (strings). OUTPUT: The function prints a table in the terminal containing all the tests computed.''' sortedData = analyzeBy(data, sortBy) if not isinstance(printSig, bool): print( 'Error: printSig must be a bool. True: the function only prints the siginificative results/ False: ' 'the function prints all the results.') else: if len(measures) % 2 == 0: fullResults = OrderedDict() for i in range(len(sortedData.keys())): groupName = sortedData.keys()[i] tempData = sortedData[sortedData.keys()[i]] results = OrderedDict() for j in range(0, len(measures), 2): testName = measures[j] + '/' + measures[j + 1] res = stats.ttest_rel(tempData[measures[j]], tempData[measures[j + 1]]) results[testName] = res fullResults[groupName] = results table_matrix = [['', 'Paired T-test', 'Test Statistic', 'p-Value']] for i in range(len(fullResults.keys())): if printSig: results = fullResults[fullResults.keys()[i]] m = results.keys() for k in range(len(m)): pVal = results[m[k]][1] if pVal < 0.05: if k == 0: table_matrix.append([ fullResults.keys()[i], m[k], results[m[k]][0], results[m[k]][1] ]) else: table_matrix.append([ '', m[k], results[m[k]][0], results[m[k]][1] ]) else: results = fullResults[fullResults.keys()[i]] m = results.keys() for k in range(len(m)): if k == 0: table_matrix.append([ fullResults.keys()[i], m[k], results[m[k]][0], results[m[k]][1] ]) else: table_matrix.append( ['', m[k], results[m[k]][0], results[m[k]][1]]) table = PT(table_matrix[0]) for row in range(1, len(table_matrix)): table.add_row(table_matrix[row]) print table else: print('Error: Measures must be paired two by two') return table_matrix