Python para Data Science e Analytics
Python para Data Science e Analytics › Guides › How to analyze an A/B test in Python and decide with statist

How to analyze an A/B test in Python and decide with statistical significance

You analyze an A/B test in Python by grouping the data by variant with Pandas, comparing the rates, and applying a test that matches the metric — a two-proportion z-test when the metric is binary conversion. The decision comes from the p-value together with the confidence interval of the difference, not from eyeballing two percentages. The step that separates analysis from guessing is fixing the metric, the hypothesis and the sample size before you look at the result.

Topics: teste A/B, estatística, experimento

What has to be defined before you compute a p-value?

The analysis starts before the code. You need one primary metric, a hypothesis written in a single sentence, and a sample size calculated before you see any data. Without that frame, a difference of two tenths of a point turns into a story and the test stops being a test.

Fixing the sample size before collection avoids the most common failure: stopping the experiment on the day the number looks favorable. Significance level, power and the smallest effect worth detecting are the three inputs that define how many observations the test needs; the common conventions are 5% for significance and 80% for power.

How do you calculate A/B test significance in Python?

The shortest path is to load the data with Pandas, group by variant, and count exposed and converted users. A groupby on the variant column over the binary conversion column gives the counts, and the conversion rate is the mean of that binary column inside each group.

For a conversion metric, which is a proportion, the appropriate test is the two-proportion z-test, available as proportions_ztest in statsmodels.stats.proportion. For continuous metrics such as average order value or session time, use the two-sample t-test from scipy.stats.ttest_ind when the distribution allows it, or the Mann-Whitney U test from scipy.stats.mannwhitneyu when the metric is skewed or carries strong outliers.

An alternative that drops the distribution assumption is the bootstrap: resample the data with NumPy thousands of times, compute the difference between variants on each resample, and read the distribution of those differences. The 95% interval of that distribution is a direct statement about effect and noise.

How do you read a p-value and a confidence interval without guessing?

The p-value is not the probability that the null hypothesis is true, and it is not the probability that the winning variant is better. It is the probability of observing a difference at least as large as the one you found if there were no real difference between variants. A p-value of 0.03 means the result is unlikely under the null hypothesis; it does not mean the decision is correct.

That is why the reading has to include the confidence interval of the difference. An interval running from 0.2% to 3.1% of lift is actionable information; an interval from -1.5% to 4.8% shows the experiment still does not separate gain from noise, even with a p-value below the cutoff.

The third element is effect size. A statistically significant difference of 0.1 percentage point may not pay for the implementation cost. Statistical significance answers whether the difference probably exists; practical relevance answers whether it is worth changing the product.

How do you know the result is real and not just noise?

The first check is the ratio between group sizes. If the variants received volumes far from the planned split, traffic allocation is broken and the result should be discarded before any calculation; a chi-square test of observed counts against the intended split is the usual check.

The second is the number of comparisons. Testing five segments and reporting the one that crossed the line inflates the false positive rate; either pre-register one primary metric or correct the thresholds, for example with Bonferroni or Holm.

The third is when you looked. Rechecking the p-value daily and stopping at the first crossing produces significance that does not replicate. Fix the horizon in advance or use a sequential method built for continuous monitoring.

Beyond those, check for duplicate user IDs, bot traffic, assignment logging errors and metric definition changes inside the test window. Novelty effects distort early results, so a week-by-week split shows whether the lift is fading.

How do you report the result so the decision holds up?

A report that survives review states the metric, the sample size per variant, the absolute and relative effect, the confidence interval of the difference, the p-value and the test used. It also states the decision rule fixed before the data arrived: what lift would justify shipping, and what would justify stopping.

Two phrasings matter. Not significant means there is not enough evidence of a difference at this sample size; it does not mean the variants are equal. And a significant but tiny effect may not cover the implementation cost, so the practical threshold belongs in the report next to the statistical one.

Where do you learn to run this analysis end to end in Python?

The workflow above depends on four things: Pandas for grouping and aggregation, NumPy for resampling, a statistics library for the tests, and a clean data pipeline before any of it. The Python for Data Science and Analytics course at python.paanalytics.net covers that stack — IDE and Jupyter Notebook setup, basic functions, NumPy and Pandas, user-defined functions, loops and conditionals, data visualization, data cleaning and preparation, and outlier detection — and continues into machine learning with linear and logistic regression, K-Means, SVM, Naive Bayes, decision trees, Random Forest, Gradient Boosting, XGBoost, LightGBM, feature selection and cross-validation.

The course is organized into three main modules — Beginner, Intermediate and Advanced — plus bonus modules, and closes with an end-to-end final project covering exploratory analysis and machine learning. Lessons are recorded in high quality and watched at your own pace, access is unlimited with no expiry date, and the course includes a completion certificate, guided exercises, projects drawn from real market work for a portfolio, and an exclusive community for networking. No prior programming knowledge is required to start.

Price is R$ 470, or 12 installments of R$ 20.37 on a credit card. Payment runs through the Hotmart checkout, by card or boleto.

Metric typeTestPython functionMain assumption
Binary conversionTwo-proportion z-teststatsmodels proportions_ztestEnough conversions in both groups
Continuous, roughly symmetricWelch's t-testscipy.stats.ttest_ind(equal_var=False)Approximate normality or large samples
Continuous, skewed or with outliersMann-Whitney Uscipy.stats.mannwhitneyuIndependent samples, rank-based comparison
Any metric, no distribution assumptionBootstrap intervalnumpy.random resamplingResamples represent the observed data

Test selection follows the metric type; function names come from the statsmodels and SciPy documentation.

Learn Python to analyze data with method

Secure payment via Hotmart, up to 12 installments.

Enroll now Product site

Frequently asked questions

Can I run an A/B test analysis in Python without a statistics background?

Yes. The test itself is a library call, such as proportions_ztest for conversion. What the library cannot decide for you is the metric, the hypothesis and the sample size, so those come first.

How large does the sample need to be before I compute significance?

It depends on the baseline rate, the smallest effect you want to detect, the significance level and the power. Set those four before collecting data; calculating the size after seeing the result defeats the purpose.

Is a p-value below 0.05 enough to ship a change?

No. A p-value below the cutoff still needs the confidence interval, the size of the effect, the implementation cost and the reliability checks — sample ratio, multiple comparisons and peeking.

Which test should I use for revenue per user?

Revenue is continuous and usually skewed, so the Mann-Whitney U test or a bootstrap interval of the difference in means is the safer default. A t-test fits when the distribution is roughly symmetric and the sample is large.

What does it mean when the result is not significant?

It means there is not enough evidence of a difference at this sample size, not that the variants are equal. Check how wide the confidence interval is and whether the test had power for the effect you care about.

Ler em português →