-
Notifications
You must be signed in to change notification settings - Fork 0
/
rjj.py
3296 lines (3116 loc) · 130 KB
/
rjj.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# !/usr/bin/env python3
__version__="0.8.5"
import argparse, os, json, csv, glob, hashlib, warnings, base64, random, math
from sklearn.base import BaseEstimator, TransformerMixin
from collections import defaultdict
from datetime import datetime
from typing import Tuple
from fpdf import FPDF
import scipy.stats as st
import scipy as sp
import numpy as np
import pandas as pd
def list_csv_files():
return [f for f in os.listdir() if f.endswith('.csv')]
def generate_report(pdf, id_val, name_val, records):
pdf.set_font('Arial', 'B', 16)
pdf.cell(0, 10, f"{id_val} - {name_val}", 0, 1, 'C')
pdf.ln(10)
table_col_widths = [50, 30, 30]
table_width = sum(table_col_widths)
page_width = pdf.w - 2 * pdf.l_margin
table_x_margin = (page_width - table_width) / 2
pdf.set_font('Arial', 'B', 12)
pdf.set_x(pdf.l_margin + table_x_margin)
pdf.cell(table_col_widths[0], 10, 'Group', 1, 0, 'C')
pdf.cell(table_col_widths[1], 10, 'Count', 1, 0, 'C')
pdf.cell(table_col_widths[2], 10, 'Minute', 1, 1, 'C')
pdf.set_font('Arial', '', 12)
total_min = 0
total_count = 0
group_summary = records.groupby(records.columns[2]).agg(
count=(records.columns[2], 'size'),
total_min=(records.columns[3], 'sum')
).reset_index()
for _, row in group_summary.iterrows():
pdf.set_x(pdf.l_margin + table_x_margin)
pdf.cell(table_col_widths[0], 10, str(row[records.columns[2]]), 1, 0, 'C')
pdf.cell(table_col_widths[1], 10, str(row['count']), 1, 0, 'C')
pdf.cell(table_col_widths[2], 10, str(row['total_min']), 1, 1, 'C')
total_min += row['total_min']
total_count += row['count']
pdf.ln(5)
pdf.set_font('Arial', 'B', 12)
pdf.set_x(pdf.l_margin + table_x_margin)
pdf.cell(table_col_widths[0], 10, 'Total', 1, 0, 'C')
pdf.cell(table_col_widths[1], 10, str(total_count), 1, 0, 'C')
pdf.cell(table_col_widths[2], 10, str(total_min), 1, 1, 'C')
class PDF(FPDF):
def header(self):
pass
def footer(self):
pass
def generate_reports():
csv_files = list_csv_files()
if csv_files:
print("CSV file(s) available. Select which one to use:")
for index, file_name in enumerate(csv_files, start=1):
print(f"{index}. {file_name}")
choice = input(f"Enter your choice (1 to {len(csv_files)}): ")
try:
choice_index=int(choice)-1
selected_file=csv_files[choice_index]
print(f"File: {selected_file} is selected!")
df = pd.read_csv(selected_file)
grouped = df.groupby([df.columns[0], df.columns[1]])
for (id_val, name_val), group in grouped:
pdf = PDF()
pdf.add_page()
generate_report(pdf, id_val, name_val, group)
pdf.output(f"{id_val}.pdf")
print(f"{id_val}.pdf created.")
print("PDF reports generated successfully.")
except (ValueError, IndexError):
print("Invalid choice. Please enter a valid number.")
else:
print("No CSV files are available in the current directory.")
input("--- Press ENTER To Exit ---")
def encode_base64(input_text):
encoded_bytes = base64.b64encode(input_text.encode('utf-8'))
encoded_text = encoded_bytes.decode('utf-8')
return encoded_text
def decode_base64(encoded_text):
decoded_bytes = base64.b64decode(encoded_text.encode('utf-8'))
decoded_text = decoded_bytes.decode('utf-8')
return decoded_text
def base64codeHandler():
choice = input("Do you want to encode or decode? (Enter 'encode' or 'decode'): ").strip().lower()
if choice == 'encode':
text_to_encode = input("Enter the text to encode: ")
encoded_text = encode_base64(text_to_encode)
print("Encoded text:", encoded_text)
elif choice == 'decode':
text_to_decode = input("Enter the Base64 text to decode: ")
try:
decoded_text = decode_base64(text_to_decode)
print("Decoded text:", decoded_text)
except Exception as e:
print("Error decoding text. Make sure it's valid Base64.")
else:
print("Invalid choice. Please enter 'encode' or 'decode'.")
def select_csv_file(csv_files):
print("Available CSV files:")
for i, file in enumerate(csv_files):
print(f"{i + 1}: {file}")
file_index = int(input("Select a CSV file by number: ")) - 1
return csv_files[file_index]
def select_csv_file_gui():
import tkinter as tk
root = tk.Tk()
icon = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "icon.png"))
root.iconphoto(False, icon)
root.withdraw()
from tkinter import filedialog
file_path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")])
return file_path
def output_as_csv_json():
input_file = select_csv_file_gui()
df = pd.read_csv(input_file)
col_id, col_group, col_min = df.columns[:3]
grouped_df = df.groupby([col_id, col_group], as_index=False)[col_min].sum()
grouped_df.to_csv('output.csv', index=False)
json_data = []
for id_value, group_data in grouped_df.groupby(col_id):
group_dict = {}
for _, row in group_data.iterrows():
group_dict[row[col_group]] = row[col_min]
json_data.append({col_id: id_value, col_group: [group_dict]})
with open('output.json', 'w') as json_file:
json.dump(json_data, json_file, indent=4)
def select_column(df):
print("Available columns:")
for i, col in enumerate(df.columns):
print(f"{i + 1}: {col}")
col_index = int(input("Select a column by number: ")) - 1
return df.columns[col_index]
def select_columns(df):
print("Available columns:")
for i, col in enumerate(df.columns):
print(f"{i + 1}: {col}")
col_index1 = int(input("Select the first column by number: ")) - 1
col_index2 = int(input("Select the second column by number: ")) - 1
return df.columns[col_index1], df.columns[col_index2]
def select_columnx(df):
print("Available columns:")
for i, col in enumerate(df.columns):
print(f"{i + 1}: {col}")
col_index1 = int(input("Select the first column by number: ")) - 1
col_index2 = int(input("Select the second column by number: ")) - 1
col_index3 = int(input("Select the third column by number: ")) - 1
return df.columns[col_index1], df.columns[col_index2], df.columns[col_index3]
def select_column_free(df):
col_index = int(input(f"Select a column by number: ")) - 1
return df.columns[col_index]
def clean_data(df, columns):
df = df[columns].replace([np.inf, -np.inf], np.nan)
df = df.dropna()
return df
def csv_to_json():
csv_files = list_csv_files()
if not csv_files:
print("No CSV files found in the current directory.")
return
print("Available CSV files:")
for i, file in enumerate(csv_files, 1):
print(f"{i}. {file}")
try:
choice = int(input("Select the CSV file by entering the corresponding number: "))
csv_file = csv_files[choice - 1]
except (ValueError, IndexError):
print("Invalid selection.")
return
try:
df = pd.read_csv(csv_file)
except Exception as e:
print(f"Error reading the file: {e}")
return
json_data = df.to_dict(orient='records')
json_file_name = os.path.splitext(csv_file)[0] + '.json'
try:
with open(json_file_name, 'w', encoding='utf-8') as json_file:
json.dump(json_data, json_file, indent=4, ensure_ascii=False)
print(f"JSON file saved as '{json_file_name}'.")
except Exception as e:
print(f"Error saving the JSON file: {e}")
def joint():
csv_files = list_csv_files()
dataframes = []
for file in csv_files:
df = pd.read_csv(file)
dataframes.append(df)
combined_df = pd.concat(dataframes, ignore_index=True)
ask = input("Enter another file name instead of output (Y/n)? ")
if ask.lower() == 'y':
given = input("Give a name to the output file: ")
output=given
else:
output="output"
combined_df.to_csv(f'{output}.csv', index=False)
def innerj():
csv_files = list_csv_files()
if csv_files:
print("CSV file(s) available. Select the 1st csv file:")
for index, file_name in enumerate(csv_files, start=1):
print(f"{index}. {file_name}")
choice = input(f"Enter your choice (1 to {len(csv_files)}): ")
choice_index=int(choice)-1
file1=csv_files[choice_index]
print("CSV file(s) available. Select the 2nd csv file:")
for index, file_name in enumerate(csv_files, start=1):
print(f"{index}. {file_name}")
choice = input(f"Enter your choice (1 to {len(csv_files)}): ")
choice_index=int(choice)-1
file2=csv_files[choice_index]
ask = input("Enter another file name instead of output (Y/n)? ")
if ask.lower() == 'y':
given = input("Give a name to the output file: ")
output=given
else:
output="output"
try:
df1 = pd.read_csv(file1)
df2 = pd.read_csv(file2)
first_column_file1 = df1.columns[0]
first_column_file2 = df2.columns[0]
merged_df = pd.merge(df1, df2, left_on=first_column_file1, right_on=first_column_file2, how='inner')
output_file = f"{output}.csv"
merged_df.to_csv(output_file, index=False)
print(f"Inner join completed and saved to {output_file}")
except (ValueError, IndexError):
print("Invalid choice. Please enter a valid number.")
else:
print("No CSV files are available in the current directory.")
def outerj():
csv_files = list_csv_files()
if csv_files:
print("CSV file(s) available. Select the 1st csv file:")
for index, file_name in enumerate(csv_files, start=1):
print(f"{index}. {file_name}")
choice = input(f"Enter your choice (1 to {len(csv_files)}): ")
choice_index=int(choice)-1
file1=csv_files[choice_index]
print("CSV file(s) available. Select the 2nd csv file:")
for index, file_name in enumerate(csv_files, start=1):
print(f"{index}. {file_name}")
choice = input(f"Enter your choice (1 to {len(csv_files)}): ")
choice_index=int(choice)-1
file2=csv_files[choice_index]
ask = input("Enter another file name instead of output (Y/n)? ")
if ask.lower() == 'y':
given = input("Give a name to the output file: ")
output=given
else:
output="output"
try:
df1 = pd.read_csv(file1)
df2 = pd.read_csv(file2)
first_column_file1 = df1.columns[0]
first_column_file2 = df2.columns[0]
merged_df = pd.merge(df1, df2, left_on=first_column_file1, right_on=first_column_file2, how='outer')
output_file = f"{output}.csv"
merged_df.to_csv(output_file, index=False)
print(f"Outer join completed and saved to {output_file}")
except (ValueError, IndexError):
print("Invalid choice. Please enter a valid number.")
else:
print("No CSV files are available in the current directory.")
def eraser():
import tkinter as tk
root = tk.Tk()
icon = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "icon.png"))
root.iconphoto(False, icon)
root.title("rjj")
root.withdraw()
from tkinter.filedialog import askopenfilename, asksaveasfilename
input_file = askopenfilename(title="Select CSV file", filetypes=[("CSV files", "*.csv")])
if not input_file:
print("No file selected. Exiting...")
return
try:
df = pd.read_csv(input_file)
print(f"Data loaded from {input_file}")
except Exception as e:
print(f"Error reading the file: {e}")
return
df_cleaned = df.drop_duplicates()
output_file = asksaveasfilename(defaultextension=".csv", filetypes=[("CSV files", "*.csv")], title="Save the cleaned file as")
if not output_file:
print("No file selected for saving. Exiting...")
return
df_cleaned.to_csv(output_file, index=False)
print(f"Cleaned data saved to {output_file}")
def mk_dir():
csv_files = list_csv_files()
if not csv_files:
print("No CSV files found in the current directory.")
return
selected_file = select_csv_file(csv_files)
df = pd.read_csv(selected_file)
print("\n* Select a column storing the folder list *\n")
selected_column = select_column(df)
for folder_name in df[selected_column].dropna().unique():
os.makedirs(str(folder_name), exist_ok=True)
print("Folders created successfully.")
def one_way_anova_v2():
file_path = select_csv_file_gui()
data = pd.read_csv(file_path)
print("\n* Reminder: 1st column should be GROUP variable *\n")
group_column, value_column = select_columns(data)
groups = data.groupby(group_column)[value_column]
group_means = groups.mean()
group_sizes = groups.size()
group_stds = groups.std(ddof=1)
f_statistic, p_value = st.f_oneway(*[group for name, group in groups])
df_between = len(groups) - 1
df_within = len(data) - len(groups)
overall_mean = data[value_column].mean()
ss_between = sum(size * (mean - overall_mean) ** 2 for size, mean in zip(group_sizes, group_means))
ss_total = sum((value - overall_mean) ** 2 for value in data[value_column])
eta_squared = ss_between / ss_total
cohen_f = np.sqrt(eta_squared / (1 - eta_squared))
alpha = 0.05
from statsmodels.stats.power import FTestAnovaPower
power_analysis = FTestAnovaPower()
power = power_analysis.power(effect_size=cohen_f,
k_groups=len(groups),
nobs=len(data),
alpha=alpha)
print("\nResults of the One-Way ANOVA:")
for group_name, mean, std in zip(group_means.index, group_means, group_stds):
print(f"Group: {group_name}, Mean: {mean:.4f}, Standard Deviation: {std:.4f}")
print(f"F({df_between}, {df_within}) = {f_statistic:.4f}")
print(f"p-value = {p_value:.4f}")
print(f"Effect Size (Cohen's f): {cohen_f:.4f}")
print(f"Power (1-β): {power:.4f}")
print("\nEffect Size calculation based on η²:")
print(f"Effect Size (Eta Squared) : {eta_squared:.4f}")
print(f"Sum of Squares Between Groups: {ss_between:.4f}")
print(f"Sum of Squares Within Groups : {ss_total-ss_between:.4f}")
print(f"Sum of Squares Total : {ss_total:.4f}")
if p_value <= 0.01: p = "p < .01"
elif p_value < 0.05 and p_value > 0.01: p = "p < .05"
else: p = f"p = {p_value:.3f}"
print(f"\nJournal/report format:\nF({df_between}, {df_within}) = {f_statistic:.3f}, {p}, η² = {eta_squared:.2f}")
from statsmodels.stats.multicomp import pairwise_tukeyhsd
tukey = pairwise_tukeyhsd(endog=data[value_column],
groups=data[group_column],
alpha=alpha)
print("\nTukey's HSD Test Results:")
print(tukey)
def independent_sample_t_test_v2():
file_path = select_csv_file_gui()
df = pd.read_csv(file_path)
col1, col2 = select_columns(df)
group_1 = df[col1].dropna()
group_2 = df[col2].dropna()
mean_1 = np.mean(group_1)
std_1 = np.std(group_1, ddof=1)
mean_2 = np.mean(group_2)
std_2 = np.std(group_2, ddof=1)
t_statistic, p_value = st.ttest_ind(group_1, group_2, equal_var=False)
d_f = len(group_1) + len(group_2) - 2
pooled_std = np.sqrt(((len(group_1) - 1) * std_1 ** 2 + (len(group_2) - 1) * std_2 ** 2) / d_f)
cohen_d = (mean_1 - mean_2) / pooled_std
alpha = 0.05
from statsmodels.stats.power import TTestIndPower
power_analysis = TTestIndPower()
power = power_analysis.power(effect_size=cohen_d, nobs1=len(group_1), ratio=len(group_2)/len(group_1), alpha=alpha, alternative='two-sided')
print("\nResults of the Independent-Sample t-Test:")
print(f"Mean (Group 1): {mean_1:.4f}")
print(f"Standard Deviation (Group 1): {std_1:.4f}")
print(f"Mean (Group 2): {mean_2:.4f}")
print(f"Standard Deviation (Group 2): {std_2:.4f}")
print(f"t({d_f}) = {t_statistic:.4f}")
print(f"p-value = {p_value:.4f}")
print(f"Effect Size (Cohen's d): {cohen_d:.4f}")
print(f"Power (1-β): {power:.4f}")
if mean_1 > mean_2: cp = ">"
elif mean_1 < mean_2: cp = "<"
else: cp = "="
if p_value <= 0.01: p = "p < .01"
elif p_value < 0.05 and p_value > 0.01: p = "p < .05"
else: p = f"p = {p_value:.3f}"
print(f"\nJournal/report format:\n{mean_1:.2f}(±{std_1:.3f}) {cp} {mean_2:.2f}(±{std_2:.3f}); t({d_f}) = {t_statistic:.3f}, {p}, d = {cohen_d:.2f}")
def paired_sample_t_test_v2():
file_path = select_csv_file_gui()
df = pd.read_csv(file_path)
col1, col2 = select_columns(df)
sample_1 = df[col1].dropna()
sample_2 = df[col2].dropna()
if len(sample_1) != len(sample_2):
raise ValueError("The two columns must have the same number of observations.")
diff = sample_1 - sample_2
mean_diff = np.mean(diff)
std_diff = np.std(diff, ddof=1)
t_statistic, p_value = st.ttest_rel(sample_1, sample_2)
d_f = len(diff) - 1
cohen_d = mean_diff / std_diff
alpha = 0.05
from statsmodels.stats.power import TTestPower
power_analysis = TTestPower()
power = power_analysis.power(effect_size=cohen_d, nobs=len(diff), alpha=alpha, alternative='two-sided')
print("\nResults of the Paired-Sample t-Test:")
print(f"Mean of Differences: {mean_diff:.4f}")
print(f"Standard Deviation of Differences (SD): {std_diff:.4f}")
print(f"t({d_f}) = {t_statistic:.4f}")
print(f"p-value = {p_value:.4f}")
print(f"Effect Size (Cohen's d): {cohen_d:.4f}")
print(f"Power (1-β): {power:.4f}")
if p_value <= 0.01: p = "p < .01"
elif p_value < 0.05 and p_value > 0.01: p = "p < .05"
else: p = f"p = {p_value:.3f}"
print(f"\nJournal/report format:\nΔ {mean_diff:.2f} ± {std_diff:.3f}; t({d_f}) = {t_statistic:.3f}, {p}, d = {cohen_d:.2f}")
def one_sample_t_test_v2():
file_path = select_csv_file_gui()
df = pd.read_csv(file_path)
selected_column = select_column(df)
sample_data = df[selected_column].dropna()
population_mean = float(input("Enter the population mean (µ): "))
t_statistic, p_value = st.ttest_1samp(sample_data, population_mean)
sample_mean = np.mean(sample_data)
sample_std = np.std(sample_data, ddof=1)
d_f = len(sample_data) - 1
cohen_d = (sample_mean - population_mean) / sample_std
alpha = 0.05
from statsmodels.stats.power import TTestPower
power_analysis = TTestPower()
power = power_analysis.power(effect_size=cohen_d, nobs=len(sample_data), alpha=alpha, alternative='two-sided')
print("\nResults of the One-Sample t-Test:")
print(f"Sample Mean: {sample_mean:.4f}")
print(f"Sample Standard Deviation (SD): {sample_std:.4f}")
print(f"t({d_f}) = {t_statistic:.4f}")
print(f"p-value = {p_value:.4f}")
print(f"Effect Size (Cohen's d): {cohen_d:.4f}")
print(f"Power (1-β): {power:.4f}")
if p_value <= 0.01: p = "p < .01"
elif p_value < 0.05 and p_value > 0.01: p = "p < .05"
else: p = f"p = {p_value:.3f}"
print(f"\nJournal/report format:\n{sample_mean:.2f} ± {sample_std:.3f}; t({d_f}) = {t_statistic:.3f}, {p}, d = {cohen_d:.2f}")
def regression_analysis(df, dependent_var, predictors):
import statsmodels.api as sm
X = df[predictors]
y = df[dependent_var]
X = sm.add_constant(X)
model = sm.OLS(y, X)
results = model.fit()
return results
def regression():
file_path = select_csv_file_gui()
if not file_path:
print("No file selected. Exiting.")
return
df = pd.read_csv(file_path)
print("Columns in the selected CSV file:", df.columns.tolist())
dependent_var = input("Enter the column name for the dependent variable: ")
if dependent_var not in df.columns:
print(f"Column '{dependent_var}' not found in the CSV file. Exiting.")
return
num_predictors = int(input("Enter the number of predictors: "))
predictors = []
for i in range(num_predictors):
predictor = input(f"Enter the column name for predictor {i+1}: ")
if predictor not in df.columns:
print(f"Column '{predictor}' not found in the CSV file. Exiting.")
return
predictors.append(predictor)
selected_columns = [dependent_var] + predictors
df_clean = clean_data(df, selected_columns)
if df_clean.empty:
print("No data left after cleaning. Exiting.")
return
results = regression_analysis(df_clean, dependent_var, predictors)
print("\nRegression Analysis Summary:")
print(results.summary())
def cronbach_alpha(df):
item_variances = df.var(axis=0, ddof=1)
total_variance = df.sum(axis=1).var(ddof=1)
n_items = df.shape[1]
alpha = (n_items / (n_items - 1)) * (1 - item_variances.sum() / total_variance)
return alpha
def cronbach_alpha_if_deleted(df):
alphas = {}
for col in df.columns:
df_subset = df.drop(columns=[col])
alpha = cronbach_alpha(df_subset)
alphas[col] = alpha
return alphas
def reliability_test():
file_path = select_csv_file_gui()
if file_path:
df = pd.read_csv(file_path)
print(f"Data loaded successfully from {file_path}")
else:
print("No file selected.")
return
print("Available columns:")
for i, col in enumerate(df.columns):
print(f"{i + 1}: {col}")
num_items = int(input("Enter the number of items (columns) within the construct: "))
selected_columns = []
for i in range(num_items):
print(f"For item {i + 1}")
col = select_column_free(df)
selected_columns.append(col)
df_clean = clean_data(df, selected_columns)
if df_clean.empty:
print("No data left after cleaning. Exiting.")
return
overall_alpha = cronbach_alpha(df_clean)
print(f"\nCronbach's alpha for the selected items is: {overall_alpha}")
alphas_if_deleted = cronbach_alpha_if_deleted(df_clean)
print("\nCronbach's alpha if an item is deleted:")
for item, alpha in alphas_if_deleted.items():
print(f" - {item}: {alpha}")
def count_and_percentage(df, column_name):
total_count = len(df[column_name])
value_counts = df[column_name].value_counts()
print(f"Results of pizza analysis for column '{column_name}':\n")
for value, count in value_counts.items():
percentage = (count / total_count) * 100
print(f"{value}\t{count} ({percentage:.0f}%)")
print("-" * 15)
print(f"Total:\t{total_count}")
ask = input("\nDo you want a pie? (Y/n) ")
if ask.lower() == "n":
print("Do tell me when you wanna a pie next time; thank you.")
else:
import tkinter as tk
root = tk.Tk()
icon = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "icon.png"))
root.iconphoto(False, icon)
root.title("rjj")
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 6))
ax.pie(value_counts, labels=value_counts.index, autopct='%1.1f%%', startangle=140)
ax.axis('equal')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
root.mainloop()
def piechart():
csv_files = list_csv_files()
if not csv_files:
print("No CSV files found in the current directory.")
return
selected_file = select_csv_file(csv_files)
df = pd.read_csv(selected_file)
column_name = select_column(df)
if column_name in df.columns:
count_and_percentage(df, column_name)
else:
print("Invalid column selected!")
def boxplot():
csv_files = list_csv_files()
if not csv_files:
print("No CSV files found in the current directory.")
return
selected_file = select_csv_file(csv_files)
df = pd.read_csv(selected_file)
selected_column = select_column(df)
data = df[selected_column].dropna()
plot_title = input("Give a title to the Plot: ")
print("Done! Please check the pop-up window for output.")
import tkinter as tk
root = tk.Tk()
icon = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "icon.png"))
root.iconphoto(False, icon)
root.title("rjj")
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.boxplot(data)
ax.set_title(plot_title)
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
root.mainloop()
def boxplots():
csv_files = list_csv_files()
if not csv_files:
print("No CSV files found in the current directory.")
return
selected_file = select_csv_file(csv_files)
df = pd.read_csv(selected_file)
print("\n* 1st column: X-axis (i.e., GROUP variable); 2nd column: Y-axis (i.e., data) *\n")
col1, col2 = select_columns(df)
group = df[col1].dropna()
data = df[col2].dropna()
xaxis = input("Give a name to X-axis (Group): ")
yaxis = input("Give a name to Y-axis (Value): ")
plot_title = input("Give a title to the Plot: ")
print("Done! Please check the pop-up window for output.")
import tkinter as tk
root = tk.Tk()
icon = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "icon.png"))
root.iconphoto(False, icon)
root.title("rjj")
import matplotlib.pyplot as plt
grouped_data = {}
for g, d in zip(group, data):
if g not in grouped_data:
grouped_data[g] = []
grouped_data[g].append(d)
box_data = [grouped_data[g] for g in grouped_data]
fig, ax = plt.subplots()
ax.boxplot(box_data, labels=grouped_data.keys())
ax.set_xlabel(xaxis)
ax.set_ylabel(yaxis)
ax.set_title(plot_title)
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
root.mainloop()
def mapper():
csv_files = list_csv_files()
if not csv_files:
print("No CSV files found in the current directory.")
return
selected_file = select_csv_file(csv_files)
df = pd.read_csv(selected_file)
print("\n* 1st column: X-axis ; 2nd column: Y-axis ; 3rd coloum: Z-axis *\n")
col1, col2, col3 = select_columnx(df)
x = df[col1].dropna()
y = df[col2].dropna()
z = df[col3].dropna()
xaxis = input("Give a name to X-axis: ")
yaxis = input("Give a name to Y-axis: ")
zaxis = input("Give a name to Z-axis: ")
title = input("Give a title to the Map: ")
print("Done! Please check the pop-up window for output.")
from scipy.interpolate import griddata
grid_x, grid_y = np.mgrid[min(x):max(x):100j, min(y):max(y):100j]
grid_z = griddata((x, y), z, (grid_x, grid_y), method='cubic')
import tkinter as tk
root = tk.Tk()
icon = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "icon.png"))
root.iconphoto(False, icon)
root.title("rjj")
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(grid_x, grid_y, grid_z, cmap='gray', edgecolor='none')
fig.colorbar(surf)
ax.set_xlabel(xaxis)
ax.set_ylabel(yaxis)
ax.set_zlabel(zaxis)
ax.set_title(title)
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
root.mainloop()
def heatmap():
ask = input("Do you want to taste a quarter? (Y/n) ")
if ask.lower() == "y":
x = np.linspace(-1, 15)
y = np.linspace(-1, 15)
title = "Quarter"
else:
x = np.linspace(-5, 5)
y = np.linspace(-5, 5)
title = "Donut"
x, y = np.meshgrid(x, y)
z = np.sin(np.sqrt(x**2 + y**2))
import tkinter as tk
root = tk.Tk()
icon = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "icon.png"))
root.iconphoto(False, icon)
root.title("rjj")
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(x, y, z, cmap='gray', edgecolor='none')
fig.colorbar(surf)
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title(title)
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
root.mainloop()
def plotter():
csv_files = list_csv_files()
if not csv_files:
print("No CSV files found in the current directory.")
return
selected_file = select_csv_file(csv_files)
df = pd.read_csv(selected_file)
print("\n* 1st column: X-axis; 2nd column: Y-axis *\n")
col1, col2 = select_columns(df)
x = df[col1].dropna()
y = df[col2].dropna()
xaxis = input("Give a name to X-axis: ")
yaxis = input("Give a name to Y-axis: ")
plot_title = input("Give a title to the Plot: ")
print("Done! Please check the pop-up window for output.")
import tkinter as tk
root = tk.Tk()
icon = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "icon.png"))
root.iconphoto(False, icon)
root.title("rjj")
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.scatter(x, y, color='black')
ax.set_xlabel(xaxis)
ax.set_ylabel(yaxis)
ax.set_title(plot_title)
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
root.mainloop()
def scatter():
csv_files = list_csv_files()
if not csv_files:
print("No CSV files found in the current directory.")
return
selected_file = select_csv_file(csv_files)
df = pd.read_csv(selected_file)
print("\n* 1st column: X-axis; 2nd column: Y-axis *\n")
col1, col2 = select_columns(df)
x = df[col1].dropna()
y = df[col2].dropna()
xaxis = input("Give a name to X-axis: ")
yaxis = input("Give a name to Y-axis: ")
plot_title = input("Give a title to the Plot: ")
print("Done! Please check the pop-up window for output.")
import tkinter as tk
root = tk.Tk()
icon = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "icon.png"))
root.iconphoto(False, icon)
root.title("rjj")
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.scatter(x, y, color='black')
ax.plot(x, y, color='black')
ax.set_xlabel(xaxis)
ax.set_ylabel(yaxis)
ax.set_title(plot_title)
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
root.mainloop()
def liner():
csv_files = list_csv_files()
if not csv_files:
print("No CSV files found in the current directory.")
return
selected_file = select_csv_file(csv_files)
df = pd.read_csv(selected_file)
print("\n* 1st column: X-axis; 2nd column: Y-axis *\n")
col1, col2 = select_columns(df)
x = df[col1].dropna()
y = df[col2].dropna()
xaxis = input("Give a name to X-axis: ")
yaxis = input("Give a name to Y-axis: ")
plot_title = input("Give a title to the Graph: ")
print("Done! Please check the pop-up window for output.")
import tkinter as tk
root = tk.Tk()
icon = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "icon.png"))
root.iconphoto(False, icon)
root.title("rjj")
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(x, y, color='black')
ax.set_xlabel(xaxis)
ax.set_ylabel(yaxis)
ax.set_title(plot_title)
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
root.mainloop()
def charter():
csv_files = list_csv_files()
if not csv_files:
print("No CSV files found in the current directory.")
return
selected_file = select_csv_file(csv_files)
df = pd.read_csv(selected_file)
print("\n* 1st column: X-axis (i.e., categories); 2nd column: Y-axis *\n")
col1, col2 = select_columns(df)
x = df[col1].dropna()
y = df[col2].dropna()
xaxis = input("Give a name to X-axis: ")
yaxis = input("Give a name to Y-axis: ")
plot_title = input("Give a title to the Chart: ")
print("Done! Please check the pop-up window for output.")
import tkinter as tk
root = tk.Tk()
icon = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "icon.png"))
root.iconphoto(False, icon)
root.title("rjj")
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.bar(x, y, color='gray')
ax.set_xlabel(xaxis)
ax.set_ylabel(yaxis)
ax.set_title(plot_title)
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
root.mainloop()
def calculate_statistics(data):
data = data.dropna()
n = len(data)
total = data.sum()
mode = data.mode()[0]
median = data.median()
mean = data.mean()
std_dev = data.std()
std_error = std_dev / (n ** 0.5)
Q0 = data.min()
Q1 = data.quantile(0.25)
Q3 = data.quantile(0.75)
Q4 = data.max()
return {
"Count": n,
"Sum": total,
"Mode": mode,
"Minimum (Q0):": Q0,
"1st Quartile:": Q1,
"Median (Q2):": median,
"3rd Quartile:": Q3,
"Maximum (Q4):": Q4,
"Mean": mean,
"Standard Deviation": std_dev,
"Standard Error": std_error,
}
def display_statistics(grouped_data):
for group, data in grouped_data:
print(f"\nStatistics for group '{group}':")
stats = calculate_statistics(data)
for stat, value in stats.items():
print(f"{stat}: {value}")
def display_column():
files = list_csv_files()
if not files:
print("No CSV files found in the current directory.")
return
csv_file = select_csv_file(files)
dataframe = pd.read_csv(csv_file)
column = select_column(dataframe)
data = dataframe[column].dropna()
stats = calculate_statistics(data)
print("\nStatistics for the selected column:")
for stat, value in stats.items():
print(f"{stat}: {value}")
def display_group():
files = list_csv_files()
if not files:
print("No CSV files found in the current directory.")
return
csv_file = select_csv_file(files)
dataframe = pd.read_csv(csv_file)
print("\n* Reminder: 1st column should be GROUP variable *\n")
group_column, data_column = select_columns(dataframe)
grouped_data = dataframe.groupby(group_column)[data_column]
display_statistics(grouped_data)
def one_sample_z_test(sample_data, population_mean, population_std):
sample_mean = np.mean(sample_data)
sample_size = len(sample_data)
standard_error = population_std / np.sqrt(sample_size)
z_score = (sample_mean - population_mean) / standard_error
p_value = 2 * (1 - st.norm.cdf(abs(z_score)))
return z_score, p_value
def one_sample_t_test(sample_data, population_mean):
t_statistic, p_value = st.ttest_1samp(sample_data, population_mean)
return t_statistic, p_value
def independent_sample_t_test(sample1, sample2):
ask = input("Equal variance assumed (Y/n)? ")
if ask.lower() == "y":
t_statistic, p_value = st.ttest_ind(sample1, sample2)
else:
t_statistic, p_value = st.ttest_ind(sample1, sample2, equal_var=False)
return t_statistic, p_value
def paired_sample_t_test(sample1, sample2):
t_statistic, p_value = st.ttest_rel(sample1, sample2)
return t_statistic, p_value
def one_way_anova(df, group_column, data_column):
groups = df.groupby(group_column)[data_column].apply(list)
F_statistic, p_value = st.f_oneway(*groups)
return F_statistic, p_value
def correlation_analysis(sample1, sample2):
r_value, p_value = st.pearsonr(sample1, sample2)
return r_value, p_value
def levene_two(sample1, sample2):
w_statistic, p_value = st.levene(sample1, sample2, center='mean')
return w_statistic, p_value
def levene_test(df, group_column, data_column):
groups = [group[data_column].values for name, group in df.groupby(group_column)]
ask = input("Center by mean (Y/n)? ")
if ask.lower() == "y":
ask2 = input("Trim the mean (Y/n)? ")
if ask2.lower() == "y":
method = "trimmed"
else: method = "mean"
else:
method = "median"
W_statistic, p_value = st.levene(*groups, center=method)
return W_statistic, p_value
def levene_t():
csv_files = list_csv_files()
if not csv_files:
print("No CSV files found in the current directory.")
return
selected_file = select_csv_file(csv_files)
df = pd.read_csv(selected_file)
col1, col2 = select_columns(df)
sample1 = df[col1].dropna()
sample2 = df[col2].dropna()
w_statistic, p_value = levene_two(sample1, sample2)
print(f"\nResults of Levene's test (centered by mean):")
print(f"W-statistic: {w_statistic}")
print(f"P-value: {p_value}")
def levene_w():
csv_files = list_csv_files()
if not csv_files:
print("No CSV files found in the current directory.")
return
selected_file = select_csv_file(csv_files)
df = pd.read_csv(selected_file)
print("\n* Reminder: 1st column should be GROUP variable *\n")
group_column, data_column = select_columns(df)
df = df[[group_column, data_column]].dropna()
W_statistic, p_value = levene_test(df, group_column, data_column)
print(f"\nResults of Levene's test of homogeneity of variance:")
print(f"W-statistic: {W_statistic}")
print(f"P-value: {p_value}")
def one_sample_z():
csv_files = list_csv_files()
if not csv_files:
print("No CSV files found in the current directory.")
return
selected_file = select_csv_file(csv_files)
df = pd.read_csv(selected_file)
selected_column = select_column(df)