ABalytics 1.0.2__tar.gz → 1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,12 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ABalytics
3
- Version: 1.0.2
3
+ Version: 1.1
4
4
  Summary: An A/B test analysis package.
5
5
  Author: Janis Berneker
6
6
  License: LICENSE
7
7
  Project-URL: Repository, https://github.com/BigBerny/abalytics
8
8
  Requires-Python: >=3.8
9
+ Description-Content-Type: text/markdown
9
10
  License-File: LICENSE
10
11
  Requires-Dist: pandas>=1.5.2
11
12
  Requires-Dist: scipy>=1.10.1
@@ -1,11 +1,12 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ABalytics
3
- Version: 1.0.2
3
+ Version: 1.1
4
4
  Summary: An A/B test analysis package.
5
5
  Author: Janis Berneker
6
6
  License: LICENSE
7
7
  Project-URL: Repository, https://github.com/BigBerny/abalytics
8
8
  Requires-Python: >=3.8
9
+ Description-Content-Type: text/markdown
9
10
  License-File: LICENSE
10
11
  Requires-Dist: pandas>=1.5.2
11
12
  Requires-Dist: scipy>=1.10.1
@@ -15,55 +15,78 @@ from .significance_tests import (
15
15
  )
16
16
 
17
17
 
18
+ class AnalysisResults:
19
+ def __init__(self, significant_results=None, info=None, sample_size=None, boolean_flag=None, levene_flag=None, gaussian_flag=None):
20
+ self.significant_results = significant_results if significant_results is not None else []
21
+ self.info = info
22
+ self.sample_size = sample_size
23
+ self.boolean_flag = boolean_flag
24
+ self.levene_flag = levene_flag
25
+ self.gaussian_flag = gaussian_flag
26
+
27
+
18
28
  def get_results(df, variable_to_analyze, group_column, p_value_threshold=0.05):
19
29
  """
20
30
  Returns a text with the results of the statistical significance tests.
21
31
 
22
32
  Parameters:
23
33
  df (pandas.DataFrame): The dataframe containing the data to analyze.
24
- variable_to_analyze (str): The column name in df that are to be analyzed for statistical significance.
34
+ variable_to_analyze (str): The column name in df that is to be analyzed for statistical significance.
25
35
  group_column (str): The name of the column in df that contains the grouping variable.
26
36
  p_value_threshold (float, optional): The threshold for determining statistical significance. Defaults to 0.05.
27
37
 
28
38
  Returns:
29
- tuple: A tuple containing the results of the statistical significance tests for each variable, and flags indicating boolean, Levene's test, and Gaussian distribution status.
39
+ AnalysisResults: An instance of the AnalysisResults class containing the following attributes:
40
+ - significant_results: A list of results of the statistical significance tests.
41
+ - info: A string containing information about the data if no results were found.
42
+ - sample_size: The sample size of the data.
43
+ - boolean_flag: A boolean flag indicating if the variable is boolean.
44
+ - levene_flag: A boolean flag indicating if Levene's test for homogeneity of variances is significant.
45
+ - gaussian_flag: A boolean flag indicating if the data has a Gaussian distribution.
30
46
  """
31
47
  if p_value_threshold > 0.05:
32
48
  print(
33
49
  "Warning: p_value_threshold is set to a value higher than the conventional alpha level of 0.05."
34
50
  )
35
51
 
36
- results = []
52
+ df = df.dropna(subset=[variable_to_analyze])
53
+ sample_size = len(df)
54
+ pvalue = None
55
+ info = None
37
56
  boolean_flag = False
38
57
  levene_flag = False
39
58
  gaussian_flag = False
40
59
  # Check if there is enough data
41
- if len(df) < 20 * df[group_column].nunique():
42
- results.append("not enough data")
60
+ if len(df) < 25 * df[group_column].nunique():
61
+ info = "not enough data"
43
62
  # Check if the variable is dichotomous (e.g. boolean)
44
63
  elif boolean_flag := is_boolean(df, variable_to_analyze):
45
64
  # Perform chi-square test
46
65
  pvalue = get_chi_square_significance(df, group_column, variable_to_analyze)
47
66
  if pvalue < p_value_threshold:
48
67
  results = get_chi_square_posthoc_results(
49
- df, group_column, variable_to_analyze
68
+ df, group_column, variable_to_analyze, p_value_threshold
50
69
  )
51
70
  elif is_numeric(df, variable_to_analyze):
52
71
  # Check homogeneity of variances. If significant, use non-parametric tests
53
- if levene_flag := is_levene_significant(df, group_column, variable_to_analyze):
72
+ if levene_flag := is_levene_significant(
73
+ df, group_column, variable_to_analyze, p_value_threshold
74
+ ):
54
75
  pvalue = get_welch_anova_significance(df, group_column, variable_to_analyze)
55
76
  if pvalue < p_value_threshold:
56
77
  results = get_games_howell_posthoc_results(
57
- df, group_column, variable_to_analyze
78
+ df, group_column, variable_to_analyze, p_value_threshold
58
79
  )
59
80
  # Check if the data has Gaussian distribution, if not use non-parametric tests
60
- elif gaussian_flag := is_gaussian(df, group_column, variable_to_analyze):
81
+ elif gaussian_flag := is_gaussian(
82
+ df, group_column, variable_to_analyze, p_value_threshold
83
+ ):
61
84
  pvalue = get_oneway_anova_significance(
62
85
  df, group_column, variable_to_analyze
63
86
  )
64
87
  if pvalue < p_value_threshold:
65
88
  results = get_tukeyhsd_posthoc_results(
66
- df, group_column, variable_to_analyze
89
+ df, group_column, variable_to_analyze, p_value_threshold
67
90
  )
68
91
  else:
69
92
  pvalue = get_crushal_wallis_significance(
@@ -71,15 +94,24 @@ def get_results(df, variable_to_analyze, group_column, p_value_threshold=0.05):
71
94
  )
72
95
  if pvalue < p_value_threshold:
73
96
  results = get_dunn_posthoc_results(
74
- df, group_column, variable_to_analyze
97
+ df, group_column, variable_to_analyze, p_value_threshold
75
98
  )
76
99
  else:
77
- results.append("Variable has to be boolean or numeric")
78
-
79
- if len(results) == 0:
80
- results.append(f"not significant (p={pvalue:.3f})")
100
+ print("Variable has to be boolean or numeric")
101
+
102
+ # If no results were found, return a message
103
+ if not 'results' in locals() or len(results.significant_results) == 0:
104
+ if pvalue is not None:
105
+ info = f"not significant (p={pvalue:.3f})"
106
+ # If results were found, return them
107
+ if 'results' in locals():
108
+ significant_results = results.significant_results
109
+ else:
110
+ significant_results = []
81
111
 
82
- return results, boolean_flag, levene_flag, gaussian_flag
112
+ return AnalysisResults(
113
+ significant_results, info, sample_size, boolean_flag, levene_flag, gaussian_flag
114
+ )
83
115
 
84
116
 
85
117
  def get_results_pretty_text_header(identifiers=None):
@@ -90,7 +122,7 @@ def get_results_pretty_text_header(identifiers=None):
90
122
  identifiers (list of str, optional): A list of strings that are to be used for identifying the data. Defaults to [].
91
123
 
92
124
  Returns:
93
- str: A formatted text string with the results of the statistical significance tests for each variable.
125
+ str: A formatted text string with the header of the pretty text table.
94
126
  """
95
127
  identifier_string = ""
96
128
  identifier_string_empty = ""
@@ -102,9 +134,9 @@ def get_results_pretty_text_header(identifiers=None):
102
134
  output_string = f"{'Identifier':<{len(identifier_string)}}{'n':>10} {'Boolean':<7} {'Levene':<6} {'Gaussian':<8} {'Result'}"
103
135
  else:
104
136
  output_string = f"{'n':>10} {'Boolean':<7} {'Levene':<6} {'Gaussian':<8} {'Result'}"
105
-
137
+
106
138
  return output_string
107
-
139
+
108
140
 
109
141
  def get_results_pretty_text(
110
142
  df,
@@ -119,18 +151,24 @@ def get_results_pretty_text(
119
151
 
120
152
  Parameters:
121
153
  df (pandas.DataFrame): The dataframe containing the data to analyze.
122
- variable_to_analyze (str): The column name in df that are to be analyzed for statistical significance.
154
+ variable_to_analyze (str): The column name in df that is to be analyzed for statistical significance.
123
155
  group_column (str): The name of the column in df that contains the grouping variable.
124
156
  identifiers (list of str, optional): A list of strings that are to be used for identifying the data. Defaults to [].
125
157
  p_value_threshold (float, optional): The threshold for determining statistical significance. Defaults to 0.05.
126
158
 
127
159
  Returns:
128
- str: A formatted text string with the results of the statistical significance tests for each variable.
160
+ str: A formatted text string with the results of the statistical significance tests.
129
161
  """
130
162
 
131
- results, boolean_flag, levene_flag, gaussian_flag = get_results(
163
+ analysis_results = get_results(
132
164
  df, variable_to_analyze, group_column, p_value_threshold
133
165
  )
166
+ significant_results = analysis_results.significant_results
167
+ info = analysis_results.info
168
+ sample_size = analysis_results.sample_size
169
+ boolean_flag = analysis_results.boolean_flag
170
+ levene_flag = analysis_results.levene_flag
171
+ gaussian_flag = analysis_results.gaussian_flag
134
172
 
135
173
  identifier_string = ""
136
174
  identifier_string_empty = ""
@@ -139,7 +177,7 @@ def get_results_pretty_text(
139
177
  identifier_string += " "
140
178
  identifier_string_empty = " ".join([""] * len(identifiers))
141
179
  identifier_string_empty += " "
142
-
180
+
143
181
  output_string = ""
144
182
  if header:
145
183
  output_string += get_results_pretty_text_header(identifiers)
@@ -150,10 +188,19 @@ def get_results_pretty_text(
150
188
  gaussian_output = "X" if gaussian_flag else ""
151
189
 
152
190
  output_results = []
153
- for i, result in enumerate(results):
154
- if i == 0:
155
- output_results.append(f"{identifier_string}{len(df):>10} {boolean_output:<7} {levene_output:<6} {gaussian_output:<8} {result}")
156
- else:
157
- output_results.append(f"{identifier_string}{len(df):>10} {boolean_output:<7} {levene_output:<6} {gaussian_output:<8} {result}")
191
+ if len(significant_results) > 0:
192
+ for i, result in enumerate(significant_results):
193
+ if i == 0:
194
+ output_results.append(
195
+ f"{identifier_string}{sample_size:>10} {boolean_output:<7} {levene_output:<6} {gaussian_output:<8} {result.result_pretty}"
196
+ )
197
+ else:
198
+ output_results.append(
199
+ f"{identifier_string}{sample_size:>10} {boolean_output:<7} {levene_output:<6} {gaussian_output:<8} {result.result_pretty}"
200
+ )
201
+ else:
202
+ output_results.append(
203
+ f"{identifier_string}{sample_size:>10} {boolean_output:<7} {levene_output:<6} {gaussian_output:<8} {info}"
204
+ )
158
205
  output_string += "\n".join(output_results)
159
206
  return output_string
@@ -0,0 +1,276 @@
1
+ import pandas as pd
2
+ from scipy import stats
3
+ from scipy.stats import normaltest, chi2_contingency
4
+ from scikit_posthocs import posthoc_dunn
5
+ from statsmodels.stats.anova import AnovaRM
6
+ from statsmodels.stats.multicomp import pairwise_tukeyhsd
7
+ from statsmodels.stats.proportion import proportions_ztest
8
+ from pingouin import pairwise_gameshowell, welch_anova
9
+ from itertools import combinations
10
+
11
+
12
+ class PosthocResult:
13
+ def __init__(self, result_pretty, p_value, groups):
14
+ self.result_pretty = result_pretty
15
+ self.p_value = p_value
16
+ self.groups = groups
17
+
18
+
19
+ class GroupResult:
20
+ def __init__(self, name, sample_size, mean, median=None):
21
+ self.name = name
22
+ self.sample_size = sample_size
23
+ self.mean = mean
24
+ self.median = median
25
+
26
+
27
+ class PosthocResults:
28
+ def __init__(self):
29
+ self.significant_results = []
30
+
31
+ def add_result(self, result_pretty, p_value, groups_info):
32
+ groups = [GroupResult(**group) for group in groups_info]
33
+ result = PosthocResult(result_pretty, p_value, groups)
34
+ self.significant_results.append(result)
35
+
36
+
37
+ def is_boolean(df, variable):
38
+ # Check if the variable is of boolean type
39
+ return df[variable].dtype == bool
40
+
41
+
42
+ def is_numeric(df, variable):
43
+ # Check if the variable is of numeric type
44
+ return df[variable].dtype in [float, int]
45
+
46
+
47
+ def is_gaussian(df, group_column, variable, p_value_threshold):
48
+ # Iterate over each unique group in the specified column
49
+ for group in df[group_column].unique():
50
+ # Subset the dataframe for the current group and test for normality
51
+ group_data = df[df[group_column] == group][variable]
52
+ _, p_value = normaltest(group_data)
53
+
54
+ # If the p-value is less than the threshold, the data is not Gaussian
55
+ if p_value < p_value_threshold:
56
+ return False # Early return if any group is not Gaussian
57
+
58
+ # If all groups passed the normality test, return True
59
+ return True
60
+
61
+
62
+ def get_chi_square_significance(df, group_column, variable):
63
+ contingency_table = pd.crosstab(df[group_column], df[variable])
64
+ _, pvalue, _, _ = chi2_contingency(contingency_table)
65
+ return pvalue
66
+
67
+
68
+ def get_chi_square_posthoc_results(df, group_column, variable, p_value_threshold):
69
+ posthoc_results = PosthocResults()
70
+ contingency_table = pd.crosstab(df[group_column], df[variable])
71
+ group_combinations = [
72
+ (group_a, group_b)
73
+ for i, group_a in enumerate(contingency_table.index)
74
+ for group_b in contingency_table.index[i + 1 :]
75
+ ]
76
+ p_values = []
77
+
78
+ for group_a, group_b in group_combinations:
79
+ if 1 not in contingency_table.columns:
80
+ continue
81
+ count = [contingency_table.loc[group_a, 1], contingency_table.loc[group_b, 1]]
82
+ nobs = [
83
+ contingency_table.loc[group_a].sum(),
84
+ contingency_table.loc[group_b].sum(),
85
+ ]
86
+ rate_a = (count[0] / nobs[0]) * 100
87
+ rate_b = (count[1] / nobs[1]) * 100
88
+
89
+ _, p_value = proportions_ztest(count, nobs)
90
+ p_values.append(p_value)
91
+
92
+ groups_info = sorted(
93
+ [
94
+ {'name': group_a, 'sample_size': nobs[0], 'mean': rate_a},
95
+ {'name': group_b, 'sample_size': nobs[1], 'mean': rate_b}
96
+ ],
97
+ key=lambda x: x['mean'],
98
+ reverse=True
99
+ )
100
+
101
+ if p_value < p_value_threshold:
102
+ result_pretty = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.1f}%) vs {groups_info[1]['name']} ({groups_info[1]['mean']:.1f}%) (p={p_value:.3f})"
103
+ posthoc_results.add_result(result_pretty, p_value, groups_info)
104
+
105
+ if len(p_values) == 0:
106
+ return posthoc_results
107
+ # Apply Bonferroni correction
108
+ corrected_alpha = p_value_threshold / len(p_values)
109
+ posthoc_results.significant_results = [
110
+ result for result in posthoc_results.significant_results if result.p_value < corrected_alpha
111
+ ]
112
+
113
+ return posthoc_results
114
+
115
+
116
+ def is_levene_significant(df, group_column, variable, p_value_threshold):
117
+ # Prepare data for homogeneity of variances test
118
+ groups = df[group_column].unique()
119
+ data_groups = [df[df[group_column] == group][variable] for group in groups]
120
+
121
+ # Perform Levene's test for equal variances
122
+ _, p_levene = stats.levene(*data_groups)
123
+
124
+ # Check if variances are equal
125
+ return p_levene < p_value_threshold
126
+
127
+
128
+ def get_welch_anova_significance(df, group_column, variable):
129
+ # Perform Welch's ANOVA
130
+ welch_anova_results = welch_anova(data=df, dv=variable, between=group_column)
131
+ # Check if the p-value from Welch's ANOVA is significant
132
+ return welch_anova_results.loc[0, "p-unc"]
133
+
134
+
135
+ def get_games_howell_posthoc_results(df, group_column, variable, p_value_threshold):
136
+ posthoc_results = PosthocResults()
137
+ games_howell_results = pairwise_gameshowell(data=df, dv=variable, between=group_column)
138
+ group_means = df.groupby(group_column)[variable].mean()
139
+ group_medians = df.groupby(group_column)[variable].median()
140
+ group_sizes = df.groupby(group_column).size()
141
+
142
+ for _, row in games_howell_results.iterrows():
143
+ p_value = row["pval"]
144
+ if p_value < p_value_threshold:
145
+ group_a, group_b = row["A"], row["B"]
146
+ mean_a, mean_b = group_means[group_a], group_means[group_b]
147
+ median_a, median_b = group_medians[group_a], group_medians[group_b]
148
+ size_a, size_b = group_sizes[group_a], group_sizes[group_b]
149
+
150
+ # Order groups so the one with the higher mean is first
151
+ groups_info = sorted(
152
+ [
153
+ {'name': group_a, 'sample_size': size_a, 'mean': mean_a, 'median': median_a},
154
+ {'name': group_b, 'sample_size': size_b, 'mean': mean_b, 'median': median_b}
155
+ ],
156
+ key=lambda x: x['mean'],
157
+ reverse=True
158
+ )
159
+
160
+ result_pretty = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.2f}) vs {groups_info[1]['name']} ({groups_info[1]['mean']:.2f}) (p={p_value:.3f})"
161
+ posthoc_results.add_result(result_pretty, p_value, groups_info)
162
+
163
+ return posthoc_results
164
+
165
+
166
+ def is_gaussian(df, group_column, variable, p_value_threshold):
167
+ # Iterate over each unique group in the specified column
168
+ for group in df[group_column].unique():
169
+ # Subset the dataframe for the current group and test for normality
170
+ group_data = df[df[group_column] == group][variable]
171
+ _, p_value = normaltest(group_data)
172
+
173
+ # If the p-value is less than the threshold, the data is not Gaussian
174
+ if p_value < p_value_threshold:
175
+ return False # Early return if any group is not Gaussian
176
+
177
+ # If all groups passed the normality test, return True
178
+ return True
179
+
180
+
181
+ def get_anova_results(df, group_column, variable):
182
+ # Perform one-way ANOVA
183
+ anova_results = AnovaRM(
184
+ data=df, depvar=variable, subject="session_id", within=[group_column]
185
+ ).fit()
186
+ return anova_results
187
+
188
+
189
+ def get_oneway_anova_significance(df, group_column, variable):
190
+ group_names = df[group_column].unique()
191
+ # Perform one-way ANOVA
192
+ group_data = [df[df[group_column] == group][variable] for group in group_names]
193
+ _, pvalue = stats.f_oneway(*group_data)
194
+ return pvalue
195
+
196
+
197
+ def get_crushal_wallis_significance(df, group_column, variable):
198
+ group_names = df[group_column].unique()
199
+ # Perform Kruskal-Wallis test
200
+ group_data = [df[df[group_column] == group][variable] for group in group_names]
201
+ _, pvalue = stats.kruskal(*group_data)
202
+ return pvalue
203
+
204
+
205
+ def get_tukeyhsd_posthoc_results(df, group_column, variable, p_value_threshold):
206
+ posthoc_results = PosthocResults()
207
+ # Perform Tukey's HSD test
208
+ tukey = pairwise_tukeyhsd(
209
+ endog=df[variable],
210
+ groups=df[group_column],
211
+ alpha=p_value_threshold,
212
+ )
213
+
214
+ # Calculate means and medians for each group
215
+ group_means = df.groupby(group_column)[variable].mean()
216
+ group_medians = df.groupby(group_column)[variable].median()
217
+ group_sizes = df.groupby(group_column).size()
218
+
219
+ # Process only significant results
220
+ significant_results = tukey._results_df[tukey._results_df["reject"] == True]
221
+ for _, row in significant_results.iterrows():
222
+ group_a, group_b = row["group1"], row["group2"]
223
+ p_value = row["p-adj"]
224
+ mean_a, mean_b = group_means[group_a], group_means[group_b]
225
+ median_a, median_b = group_medians[group_a], group_medians[group_b]
226
+ size_a, size_b = group_sizes[group_a], group_sizes[group_b]
227
+
228
+ # Order groups so the one with the higher mean is first
229
+ groups_info = sorted(
230
+ [
231
+ {'name': group_a, 'sample_size': size_a, 'mean': mean_a, 'median': median_a},
232
+ {'name': group_b, 'sample_size': size_b, 'mean': mean_b, 'median': median_b}
233
+ ],
234
+ key=lambda x: x['mean'],
235
+ reverse=True
236
+ )
237
+
238
+ result_pretty = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.2f}) vs {groups_info[1]['name']} ({groups_info[1]['mean']:.2f}) (p={p_value:.3f})"
239
+ posthoc_results.add_result(result_pretty, p_value, groups_info)
240
+
241
+ return posthoc_results
242
+
243
+
244
+ def get_dunn_posthoc_results(df, group_column, variable, p_value_threshold):
245
+ posthoc_results = PosthocResults()
246
+ # Perform Dunn's test
247
+ dunn_results = posthoc_dunn(
248
+ df,
249
+ val_col=variable,
250
+ group_col=group_column,
251
+ p_adjust="holm",
252
+ )
253
+ group_means = df.groupby(group_column)[variable].mean()
254
+ group_medians = df.groupby(group_column)[variable].median()
255
+ group_sizes = df.groupby(group_column).size()
256
+
257
+ for group_a, group_b in combinations(dunn_results.index, 2):
258
+ p_value = dunn_results.at[group_a, group_b]
259
+ if p_value < p_value_threshold:
260
+ mean_a, mean_b = group_means[group_a], group_means[group_b]
261
+ median_a, median_b = group_medians[group_a], group_medians[group_b]
262
+ size_a, size_b = group_sizes[group_a], group_sizes[group_b]
263
+
264
+ # Order groups so the one with the higher mean is first
265
+ groups_info = sorted(
266
+ [
267
+ {'name': group_a, 'sample_size': size_a, 'mean': mean_a, 'median': median_a},
268
+ {'name': group_b, 'sample_size': size_b, 'mean': mean_b, 'median': median_b}
269
+ ],
270
+ key=lambda x: x['mean'],
271
+ reverse=True
272
+ )
273
+
274
+ result_pretty = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.2f}) vs {groups_info[1]['name']} ({groups_info[1]['mean']:.2f}) (p={p_value:.3f})"
275
+ posthoc_results.add_result(result_pretty, p_value, groups_info)
276
+ return posthoc_results
@@ -2,12 +2,13 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name='ABalytics',
5
- version='1.0.2',
5
+ version='1.1',
6
6
  author='Janis Berneker',
7
7
  packages=find_packages(),
8
8
  license='LICENSE',
9
9
  description='An A/B test analysis package.',
10
10
  long_description=open('README.md').read(),
11
+ long_description_content_type='text/markdown',
11
12
  install_requires=[
12
13
  'pandas>=1.5.2',
13
14
  'scipy>=1.10.1',
@@ -1,216 +0,0 @@
1
- import pandas as pd
2
- from scipy import stats
3
- from scipy.stats import normaltest, chi2_contingency
4
- from scikit_posthocs import posthoc_dunn
5
- from statsmodels.stats.anova import AnovaRM
6
- from statsmodels.stats.multicomp import pairwise_tukeyhsd
7
- from statsmodels.stats.proportion import proportions_ztest
8
- from pingouin import pairwise_gameshowell, welch_anova
9
-
10
- p_value_threshold = 0.05 # Set the p-value threshold to 0.05
11
-
12
- def is_boolean(df, variable):
13
- # Check if the variable is of boolean type
14
- return df[variable].dtype == bool
15
-
16
- def is_numeric(df, variable):
17
- # Check if the variable is of numeric type
18
- return df[variable].dtype in [float, int]
19
-
20
- def is_gaussian(df, group_column, variable, p_value_threshold):
21
- # Iterate over each unique group in the specified column
22
- for group in df[group_column].unique():
23
- # Subset the dataframe for the current group and test for normality
24
- group_data = df[df[group_column] == group][variable]
25
- _, p_value = normaltest(group_data)
26
-
27
- # If the p-value is less than the threshold, the data is not Gaussian
28
- if p_value < p_value_threshold:
29
- return False # Early return if any group is not Gaussian
30
-
31
- # If all groups passed the normality test, return True
32
- return True
33
-
34
-
35
- def get_chi_square_significance(df, group_column, variable):
36
- contingency_table = pd.crosstab(df[group_column], df[variable])
37
- _, pvalue, _, _ = chi2_contingency(contingency_table)
38
- return pvalue
39
-
40
- def get_chi_square_posthoc_results(df, group_column, variable):
41
- results = []
42
- contingency_table = pd.crosstab(df[group_column], df[variable])
43
- group_combinations = [(group_a, group_b) for i, group_a in enumerate(contingency_table.index) for group_b in contingency_table.index[i + 1:]]
44
- p_values = []
45
-
46
- for group_a, group_b in group_combinations:
47
- count = [contingency_table.loc[group_a, 1], contingency_table.loc[group_b, 1]]
48
- nobs = [contingency_table.loc[group_a].sum(), contingency_table.loc[group_b].sum()]
49
- rate_a = (count[0] / nobs[0]) * 100
50
- rate_b = (count[1] / nobs[1]) * 100
51
-
52
- _, p_value = proportions_ztest(count, nobs)
53
- p_values.append(p_value)
54
-
55
- if p_value < p_value_threshold:
56
- if rate_a > rate_b:
57
- results.append(f"{group_a} ({rate_a:.1f}%) > {group_b} ({rate_b:.1f}%) (p={p_value:.3f})")
58
- else:
59
- results.append(f"{group_b} ({rate_b:.1f}%) > {group_a} ({rate_a:.1f}%) (p={p_value:.3f})")
60
-
61
- # Apply Bonferroni correction
62
- corrected_alpha = p_value_threshold / len(p_values)
63
- results_corrected = [result for result, p_value in zip(results, p_values) if p_value < corrected_alpha]
64
-
65
- return results_corrected if results_corrected else results
66
-
67
- def is_levene_significant(df, group_column, variable):
68
- # Prepare data for homogeneity of variances test
69
- groups = df[group_column].unique()
70
- data_groups = [
71
- df[df[group_column] == group][variable] for group in groups
72
- ]
73
-
74
- # Perform Levene's test for equal variances
75
- _, p_levene = stats.levene(*data_groups)
76
-
77
- # Check if variances are equal
78
- return p_levene < p_value_threshold
79
-
80
- def get_welch_anova_significance(df, group_column, variable):
81
- # Perform Welch's ANOVA
82
- welch_anova_results = welch_anova(
83
- data=df,
84
- dv=variable,
85
- between=group_column
86
- )
87
- # Check if the p-value from Welch's ANOVA is significant
88
- return welch_anova_results.loc[0, "p-unc"]
89
-
90
- def get_games_howell_posthoc_results(df, group_column, variable):
91
- results = []
92
- posthoc_results = pairwise_gameshowell(
93
- data=df,
94
- dv=variable,
95
- between=group_column
96
- )
97
- # Iterate through the posthoc results and append significant comparisons
98
- for _, row in posthoc_results.iterrows():
99
- if row['pval'] < p_value_threshold:
100
- group_a = row['A']
101
- group_b = row['B']
102
- mean_diff = row['mean(A)'] - row['mean(B)']
103
- p_value = row['pval']
104
- mean_a = df[df[group_column] == group_a][variable].mean()
105
- mean_b = df[df[group_column] == group_b][variable].mean()
106
- if mean_diff > 0:
107
- results.append(
108
- f"{group_a} ({mean_a:.2f}) > {group_b} ({mean_b:.2f}) (p={p_value:.3f})"
109
- )
110
- else:
111
- results.append(
112
- f"{group_b} ({mean_b:.2f}) > {group_a} ({mean_a:.2f}) (p={p_value:.3f})"
113
- )
114
- return results
115
-
116
-
117
- def is_gaussian(df, group_column, variable):
118
- # Iterate over each unique group in the specified column
119
- for group in df[group_column].unique():
120
- # Subset the dataframe for the current group and test for normality
121
- group_data = df[df[group_column] == group][variable]
122
- _, p_value = normaltest(group_data)
123
-
124
- # If the p-value is less than the threshold, the data is not Gaussian
125
- if p_value < p_value_threshold:
126
- return False # Early return if any group is not Gaussian
127
-
128
- # If all groups passed the normality test, return True
129
- return True
130
-
131
- def get_anova_results(df, group_column, variable):
132
- # Perform one-way ANOVA
133
- anova_results = AnovaRM(
134
- data=df,
135
- depvar=variable,
136
- subject="session_id",
137
- within=[group_column]
138
- ).fit()
139
- return anova_results
140
-
141
- def get_oneway_anova_significance(df, group_column, variable):
142
- group_names = df[group_column].unique()
143
- # Perform one-way ANOVA
144
- group_data = [df[df[group_column] == group][variable] for group in group_names]
145
- _, pvalue = stats.f_oneway(*group_data)
146
- return pvalue
147
-
148
- def get_crushal_wallis_significance(df, group_column, variable):
149
- group_names = df[group_column].unique()
150
- # Perform Kruskal-Wallis test
151
- group_data = [df[df[group_column] == group][variable] for group in group_names]
152
- _, pvalue = stats.kruskal(*group_data)
153
- return pvalue
154
-
155
- def get_tukeyhsd_posthoc_results(df, group_column, variable):
156
- # Perform Tukey's HSD test
157
- tukey = pairwise_tukeyhsd(
158
- endog=df[variable],
159
- groups=df[group_column],
160
- alpha=p_value_threshold,
161
- )
162
-
163
- # Calculate means for each group
164
- group_means = df.groupby(group_column)[
165
- variable
166
- ].mean()
167
- results = []
168
- # Print only significant results
169
- significant_results = tukey._results_df[
170
- tukey._results_df["reject"] == True
171
- ]
172
- for _, row in significant_results.iterrows():
173
- group_a = row["group1"]
174
- group_b = row["group2"]
175
- mean_diff = row["meandiff"]
176
- p_value = row["p-adj"]
177
- mean_a = group_means[group_a]
178
- mean_b = group_means[group_b]
179
-
180
- if mean_diff > 0:
181
- results.append(
182
- f"{group_a} ({mean_a:.2f}) > {group_b} ({mean_b:.2f}) (p={p_value:.3f})"
183
- )
184
- else:
185
- results.append(
186
- f"{group_b} ({mean_b:.2f}) > {group_a} ({mean_a:.2f}) (p={p_value:.3f})"
187
- )
188
- return results
189
-
190
- def get_dunn_posthoc_results(df, group_column, variable):
191
- results = []
192
- # Perform Dunn's test
193
- dunn_results = posthoc_dunn(
194
- df,
195
- val_col=variable,
196
- group_col=group_column,
197
- p_adjust="holm",
198
- )
199
- group_means = df.groupby(group_column)[
200
- variable
201
- ].mean()
202
- for i, group_a in enumerate(dunn_results.index):
203
- for group_b in dunn_results.columns[i + 1 :]:
204
- p_value = dunn_results.loc[group_a, group_b]
205
- # Check if the p-value is less than 0.05
206
- if p_value < p_value_threshold:
207
- # Compare means of the two groups
208
- if group_means[group_a] > group_means[group_b]:
209
- results.append(
210
- f"{group_a} ({group_means[group_a]:.2f}) > {group_b} ({group_means[group_b]:.2f}) (p={p_value:.3f})"
211
- )
212
- else:
213
- results.append(
214
- f"{group_b} ({group_means[group_b]:.2f}) > {group_a} ({group_means[group_a]:.2f}) (p={p_value:.3f})"
215
- )
216
- return results
File without changes
File without changes
File without changes
File without changes