ABalytics 2.1.0__tar.gz → 2.1.2__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,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: abalytics
3
- Version: 2.1.0
3
+ Version: 2.1.2
4
4
  Summary: Advanced A/B Testing Statistical Analytics
5
5
  Author: Janis Berneker
6
6
  License: LICENSE
@@ -76,8 +76,7 @@ def is_gaussian(
76
76
  """Check if a variable or grouped variables in a DataFrame follow a Gaussian distribution."""
77
77
  if group_column:
78
78
  return all(
79
- normaltest(df[df[group_column] == group][variable])[1]
80
- >= p_value_threshold
79
+ normaltest(df[df[group_column] == group][variable])[1] >= p_value_threshold
81
80
  for group in df[group_column].unique()
82
81
  )
83
82
  return normaltest(df[variable])[1] >= p_value_threshold
@@ -93,64 +92,6 @@ def get_chi_square_significance(
93
92
 
94
93
  def get_chi_square_posthoc_results(
95
94
  df: pd.DataFrame, group_column: str, variable: str, p_value_threshold: float
96
- ) -> PosthocResults:
97
- posthoc_results = PosthocResults()
98
- contingency_table = pd.crosstab(df[group_column], df[variable])
99
- group_combinations = [
100
- (group_a, group_b)
101
- for i, group_a in enumerate(contingency_table.index)
102
- for group_b in contingency_table.index[i + 1 :]
103
- ]
104
- p_values: List[float] = []
105
-
106
- assert set(contingency_table.columns).issubset(
107
- {0, 1, False, True}
108
- ), "Columns must be 0/1 or False/True."
109
-
110
- for group_a, group_b in group_combinations:
111
- true_or_one = 1 if 1 in contingency_table.columns else True
112
- count = [
113
- contingency_table.loc[group_a, true_or_one],
114
- contingency_table.loc[group_b, true_or_one],
115
- ]
116
- nobs = [
117
- contingency_table.loc[group_a].sum(),
118
- contingency_table.loc[group_b].sum(),
119
- ]
120
- rate_a = (count[0] / nobs[0]) * 100
121
- rate_b = (count[1] / nobs[1]) * 100
122
-
123
- _, p_value = proportions_ztest(count, nobs)
124
- p_values.append(p_value)
125
-
126
- groups_info = sorted(
127
- [
128
- {"name": group_a, "sample_size": nobs[0], "mean": rate_a},
129
- {"name": group_b, "sample_size": nobs[1], "mean": rate_b},
130
- ],
131
- key=lambda x: x["mean"],
132
- reverse=True,
133
- )
134
-
135
- if p_value < p_value_threshold:
136
- result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.1f}%) > {groups_info[1]['name']} ({groups_info[1]['mean']:.1f}%) (p={p_value:.3f})"
137
- posthoc_results.add_result(result_pretty_text, p_value, groups_info)
138
-
139
- if len(p_values) == 0:
140
- return posthoc_results
141
- # Apply Bonferroni correction
142
- corrected_alpha = p_value_threshold / len(p_values)
143
- posthoc_results.significant_results = [
144
- result
145
- for result in posthoc_results.significant_results
146
- if result.p_value < corrected_alpha
147
- ]
148
-
149
- return posthoc_results
150
-
151
-
152
- def get_chi_square_posthoc_results_new(
153
- df: pd.DataFrame, group_column: str, variable: str, p_value_threshold: float
154
95
  ) -> PosthocResults:
155
96
  """Perform posthoc analysis for chi-square test results."""
156
97
  posthoc_results = PosthocResults()
@@ -158,12 +99,15 @@ def get_chi_square_posthoc_results_new(
158
99
  group_combinations = list(combinations(contingency_table.index, 2))
159
100
  p_values = []
160
101
 
102
+ # Determine whether to use True/False or 0/1 based on the columns present in the contingency table
103
+ true_or_one = 1 if 1 in contingency_table.columns else True
104
+
161
105
  for group_a, group_b in group_combinations:
162
- if 1 not in contingency_table.columns:
106
+ if true_or_one not in contingency_table.columns:
163
107
  continue
164
108
  count = [
165
- contingency_table.loc[group_a, 1],
166
- contingency_table.loc[group_b, 1],
109
+ contingency_table.loc[group_a, true_or_one],
110
+ contingency_table.loc[group_b, true_or_one],
167
111
  ]
168
112
  nobs = [
169
113
  contingency_table.loc[group_a].sum(),
@@ -174,12 +118,14 @@ def get_chi_square_posthoc_results_new(
174
118
  p_values.append(p_value)
175
119
 
176
120
  if p_value < p_value_threshold:
177
- groups_info = [
178
- {"name": group, "sample_size": nobs[i], "mean": rate}
179
- for i, (group, rate) in enumerate(
180
- zip([group_a, group_b], [rate_a, rate_b])
181
- )
182
- ]
121
+ groups_info = sorted(
122
+ [
123
+ {"name": group_a, "sample_size": nobs[0], "mean": rate_a},
124
+ {"name": group_b, "sample_size": nobs[1], "mean": rate_b},
125
+ ],
126
+ key=lambda x: x["mean"],
127
+ reverse=True,
128
+ )
183
129
  result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.1f}%) > {groups_info[1]['name']} ({groups_info[1]['mean']:.1f}%) (p={p_value:.3f})"
184
130
  posthoc_results.add_result(result_pretty_text, p_value, groups_info)
185
131
 
@@ -212,8 +158,7 @@ def is_levene_significant(
212
158
  """
213
159
  # Extract data for each group
214
160
  data_groups = [
215
- df[df[group_column] == group][variable]
216
- for group in df[group_column].unique()
161
+ df[df[group_column] == group][variable] for group in df[group_column].unique()
217
162
  ]
218
163
  # Perform Levene's test
219
164
  _, p_value = stats.levene(*data_groups)
@@ -236,9 +181,7 @@ def get_welch_anova_significance(
236
181
  - float: The p-value from Welch's ANOVA.
237
182
  """
238
183
  # Perform Welch's ANOVA and return the p-value
239
- return welch_anova(data=df, dv=variable, between=group_column).loc[
240
- 0, "p-unc"
241
- ]
184
+ return welch_anova(data=df, dv=variable, between=group_column).loc[0, "p-unc"]
242
185
 
243
186
 
244
187
  def get_games_howell_posthoc_results(
@@ -263,9 +206,7 @@ def get_games_howell_posthoc_results(
263
206
  )
264
207
  # Aggregate group statistics
265
208
  group_stats = (
266
- df.groupby(group_column)[variable]
267
- .agg(["mean", "median", "size"])
268
- .reset_index()
209
+ df.groupby(group_column)[variable].agg(["mean", "median", "size"]).reset_index()
269
210
  )
270
211
 
271
212
  # Filter significant results and add to posthoc results
@@ -273,12 +214,8 @@ def get_games_howell_posthoc_results(
273
214
  games_howell_results["pval"] < p_value_threshold
274
215
  ]
275
216
  for _, row in significant_results.iterrows():
276
- group_a_stats = group_stats[group_stats[group_column] == row["A"]].iloc[
277
- 0
278
- ]
279
- group_b_stats = group_stats[group_stats[group_column] == row["B"]].iloc[
280
- 0
281
- ]
217
+ group_a_stats = group_stats[group_stats[group_column] == row["A"]].iloc[0]
218
+ group_b_stats = group_stats[group_stats[group_column] == row["B"]].iloc[0]
282
219
  groups_info = sorted(
283
220
  [
284
221
  {
@@ -318,8 +255,7 @@ def get_oneway_anova_significance(
318
255
  - float: The p-value from the one-way ANOVA test.
319
256
  """
320
257
  group_data = [
321
- df[df[group_column] == group][variable]
322
- for group in df[group_column].unique()
258
+ df[df[group_column] == group][variable] for group in df[group_column].unique()
323
259
  ]
324
260
  _, p_value = stats.f_oneway(*group_data)
325
261
  return p_value
@@ -340,8 +276,7 @@ def get_crushal_wallis_significance(
340
276
  - float: The p-value from the Kruskal-Wallis H-test.
341
277
  """
342
278
  group_data = [
343
- df[df[group_column] == group][variable]
344
- for group in df[group_column].unique()
279
+ df[df[group_column] == group][variable] for group in df[group_column].unique()
345
280
  ]
346
281
  _, p_value = stats.kruskal(*group_data)
347
282
  return p_value
@@ -367,20 +302,14 @@ def get_tukeyhsd_posthoc_results(
367
302
  endog=df[variable], groups=df[group_column], alpha=p_value_threshold
368
303
  )
369
304
  group_stats = (
370
- df.groupby(group_column)[variable]
371
- .agg(["mean", "median", "size"])
372
- .reset_index()
305
+ df.groupby(group_column)[variable].agg(["mean", "median", "size"]).reset_index()
373
306
  )
374
307
 
375
308
  significant_results = tukey._results_df[tukey._results_df["reject"]]
376
309
  for _, row in significant_results.iterrows():
377
310
  group_a, group_b = row["group1"], row["group2"]
378
- group_a_stats = group_stats.loc[
379
- group_stats[group_column] == group_a
380
- ].iloc[0]
381
- group_b_stats = group_stats.loc[
382
- group_stats[group_column] == group_b
383
- ].iloc[0]
311
+ group_a_stats = group_stats.loc[group_stats[group_column] == group_a].iloc[0]
312
+ group_b_stats = group_stats.loc[group_stats[group_column] == group_b].iloc[0]
384
313
  groups_info = sorted(
385
314
  [
386
315
  {
@@ -400,9 +329,7 @@ def get_tukeyhsd_posthoc_results(
400
329
  reverse=True,
401
330
  )
402
331
  result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.2f}) > {groups_info[1]['name']} ({groups_info[1]['mean']:.2f}) (p={row['p-adj']:.3f})"
403
- posthoc_results.add_result(
404
- result_pretty_text, row["p-adj"], groups_info
405
- )
332
+ posthoc_results.add_result(result_pretty_text, row["p-adj"], groups_info)
406
333
 
407
334
  return posthoc_results
408
335
 
@@ -427,9 +354,7 @@ def get_dunn_posthoc_results(
427
354
  df, val_col=variable, group_col=group_column, p_adjust="holm"
428
355
  )
429
356
  group_stats = (
430
- df.groupby(group_column)[variable]
431
- .agg(["mean", "median", "size"])
432
- .reset_index()
357
+ df.groupby(group_column)[variable].agg(["mean", "median", "size"]).reset_index()
433
358
  )
434
359
 
435
360
  for group_pair, p_value in enumerate(dunn_results.values.flatten()):
@@ -586,9 +511,7 @@ def get_repeated_measures_anova_posthoc_results(
586
511
  # Sort groups by mean for consistent presentation
587
512
  groups_info.sort(key=lambda x: x["mean"], reverse=True)
588
513
  result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.2f}) > {groups_info[1]['name']} ({groups_info[1]['mean']:.2f}) (p={p_val_corrected:.3f})"
589
- posthoc_results.add_result(
590
- result_pretty_text, p_val_corrected, groups_info
591
- )
514
+ posthoc_results.add_result(result_pretty_text, p_val_corrected, groups_info)
592
515
 
593
516
  return posthoc_results
594
517
 
@@ -673,9 +596,7 @@ def get_nemenyi_results(
673
596
  posthoc_results = PosthocResults()
674
597
  posthoc = posthoc_nemenyi_friedman(df[variables_to_compare])
675
598
 
676
- for (i, var1), (j, var2) in combinations(
677
- enumerate(variables_to_compare), 2
678
- ):
599
+ for (i, var1), (j, var2) in combinations(enumerate(variables_to_compare), 2):
679
600
  posthoc_p_value = posthoc.iloc[i, j]
680
601
  if posthoc_p_value < p_value_threshold:
681
602
  groups_info = [
@@ -690,8 +611,6 @@ def get_nemenyi_results(
690
611
  groups_info.sort(key=lambda x: x["mean"], reverse=True)
691
612
 
692
613
  result_pretty_text = f"{groups_info[0]['name']} ({groups_info[0]['mean']:.2f}) > {groups_info[1]['name']} ({groups_info[1]['mean']:.2f}) (p={posthoc_p_value:.3f})"
693
- posthoc_results.add_result(
694
- result_pretty_text, posthoc_p_value, groups_info
695
- )
614
+ posthoc_results.add_result(result_pretty_text, posthoc_p_value, groups_info)
696
615
 
697
616
  return posthoc_results
@@ -3,7 +3,7 @@ from typing import Optional, List
3
3
  import pandas as pd
4
4
 
5
5
 
6
- def get_table_header(max_identifier_length) -> str:
6
+ def get_table_header(max_identifier_length: int) -> str:
7
7
  """
8
8
  Returns a text with the results of the statistical significance tests.
9
9
 
@@ -23,7 +23,7 @@ def format_results_as_table(
23
23
  header: bool = True,
24
24
  identifiers_list: Optional[List[List[str]]] = None,
25
25
  show_only_significant_results: bool = False,
26
- ):
26
+ ) -> str:
27
27
  """
28
28
  Returns a text with the results of the statistical significance tests.
29
29
 
@@ -59,8 +59,6 @@ def format_results_as_table(
59
59
  s.ljust(max_identifier_length) for s in identifier_string_list
60
60
  ]
61
61
 
62
- output_string = ""
63
-
64
62
  if header:
65
63
  output_string += get_table_header(max_identifier_length)
66
64
  output_string += "\n"
@@ -95,7 +93,7 @@ def format_results_as_table(
95
93
  output_results.append(
96
94
  f"{identifier_string}{sample_size:>10} {levene_output:<6} {gaussian_output:<8} {info}"
97
95
  )
98
- output_string += "\n".join(output_results)
96
+ output_string = "\n".join(output_results)
99
97
  return output_string
100
98
 
101
99
 
@@ -116,10 +114,12 @@ def convert_long_to_wide(
116
114
  pd.DataFrame: The DataFrame converted to wide format, with optional column flattening.
117
115
  """
118
116
  # Create a pivot table with multi-level columns
119
- wide_df = df.pivot_table(index=index_col, columns=columns_col, aggfunc='first')
117
+ wide_df = df.pivot_table(index=index_col, columns=columns_col, aggfunc="first")
120
118
 
121
119
  if flatten_columns:
122
120
  # Flatten the multi-level columns and create combined column names
123
- wide_df.columns = ["{}_{}".format(col[0], col[1]) for col in wide_df.columns.values]
121
+ wide_df.columns = [
122
+ "{}_{}".format(col[0], col[1]) for col in wide_df.columns.values
123
+ ]
124
124
 
125
125
  return wide_df.reset_index()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: abalytics
3
- Version: 2.1.0
3
+ Version: 2.1.2
4
4
  Summary: Advanced A/B Testing Statistical Analytics
5
5
  Author: Janis Berneker
6
6
  License: LICENSE
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name='abalytics',
5
- version='2.1.0',
5
+ version='2.1.2',
6
6
  author='Janis Berneker',
7
7
  packages=find_packages(),
8
8
  license='LICENSE',
File without changes
File without changes
File without changes