English

One-Way ANOVA in Python: F-Test, Tukey Post Hoc, and Assumptions

One-way ANOVA in Python tests whether the means of three or more groups differ, using scipy.stats.f_oneway for a quick F-test or statsmodels for a complete ANOVA table.

One-Way ANOVA in Python: F-Test, Tukey Post Hoc, and Assumptions
Contents
  1. Preparing the data
  2. Converting wide data to long format
  3. Exploring the groups with a boxplot
  4. Running the F-test
  5. Producing a complete ANOVA table
  6. Post hoc test: which treatments differ?
  7. Checking the assumptions
  8. What if the assumptions are not met?
  9. How large is the effect?
  10. How to report one-way ANOVA results
  11. Frequently asked questions
  12. Which Python function performs one-way ANOVA?
  13. What should be done after a significant ANOVA?
  14. Can one-way ANOVA be used for only two groups?
  15. What is the difference between one-way and two-way ANOVA?
  16. Is Python accepted for ANOVA in a thesis?
  17. How many replications per group are needed for one-way ANOVA?
  18. Does the order of groups matter in the analysis?
  19. Can unequal group sizes be analyzed?
  20. What is the difference between Tukey HSD and the Duncan test?
  21. References

Versi bahasa Indonesia: One Way ANOVA (Rancangan Percobaan) dengan Python

Short answer: one-way ANOVA in Python tests whether the means of three or more groups differ, using scipy.stats.f_oneway for a quick F-test or statsmodels for a complete ANOVA table. When the F-test is significant (p < 0.05), a post hoc test such as Tukey’s HSD identifies which pairs of groups differ. In the worked example with four treatments, the F-statistic equals 4.904 with p = 0.00409, so at least one treatment mean differs from the others.

One-way analysis of variance is a standard tool for researchers and data analysts who compare the average of three or more groups. It is not limited to designed experiments; any continuous outcome measured on an interval or ratio scale and grouped by one categorical factor can be analyzed the same way. Python is free, reproducible, and accepted in scientific publications, which makes it a practical alternative to SPSS or SAS. The analytical sequence remains the same in any software: compute the F-test first, then run a post hoc test only if the F-test is significant.

Preparing the data

The example file data.csv stores the observations in wide format: one column for each treatment (A, B, C, and D), with replications in rows. Keeping the file name and column names unchanged is advisable for beginners, because the code refers to them directly. The file is placed in the working folder of Jupyter Notebook, which is opened from the command prompt.

CSV data in wide format with treatment columns A, B, C, and D
Example data in wide format.
import pandas as pd

df = pd.read_csv("data.csv")
print(df.head())

Converting wide data to long format

Most statistical functions expect long format, with one column for the group label and one column for the value, exactly as data are arranged in SPSS. The melt function performs the conversion.

df_melt = pd.melt(df.reset_index(), id_vars=["index"],
                  value_vars=["A", "B", "C", "D"])
df_melt.columns = ["index", "treatments", "value"]
print(df_melt.head())
print(df_melt.tail())

If the CSV file is already in long format, this step can be skipped; in that case, every later reference to df_melt should be replaced with df.

Exploring the groups with a boxplot

import matplotlib.pyplot as plt
import seaborn as sns

ax = sns.boxplot(x="treatments", y="value", data=df_melt, color="#99c2a2")
ax = sns.swarmplot(x="treatments", y="value", data=df_melt, color="#7d0013")
plt.savefig("boxplot.png")
plt.show()
Boxplot with individual points for treatments A, B, C, and D showing a visible difference between A and C
Boxplot of the four treatments.

The boxplot suggests a visible difference between treatments A and C. However, a visual impression is not evidence; the ANOVA and post hoc tests provide the formal answer.

Running the F-test

The hypotheses are as follows. H0: all four treatment means are equal. H1: at least one treatment mean differs from the others.

import scipy.stats as stats

fvalue, pvalue = stats.f_oneway(df["A"], df["B"], df["C"], df["D"])
print(fvalue, pvalue)
Python output showing F statistic 4.904 and p-value 0.00409
F = 4.904, p = 0.00409.

The F-statistic equals 4.904 and the p-value equals 0.00409. Because p is below 0.05, H0 is rejected: at least one treatment differs significantly from the others.

Producing a complete ANOVA table

Reports and theses usually require the full table with sums of squares and degrees of freedom. The statsmodels package provides it through an OLS model with a categorical predictor.

import statsmodels.api as sm
from statsmodels.formula.api import ols

model = ols("value ~ C(treatments)", data=df_melt).fit()
anova_table = sm.stats.anova_lm(model, typ=2)
anova_table["mean_sq"] = anova_table["sum_sq"] / anova_table["df"]
print(anova_table)
Statsmodels ANOVA table with sum of squares, degrees of freedom, F, and probability
ANOVA table from statsmodels.

The table repeats the same conclusion, F = 4.9 with p = 0.004. The last line of code adds the mean square column, which anova_lm does not print by default. The original exercise used the bioinfokit package for this purpose; computing the column directly avoids an extra dependency. When Python reports ModuleNotFoundError at any step, the missing package must be installed from the command prompt with pip install followed by the package name, and the notebook kernel restarted.

Post hoc test: which treatments differ?

A significant F-test only says that some difference exists. Tukey’s honestly significant difference (HSD) test compares every pair while controlling the overall error rate.

from statsmodels.stats.multicomp import pairwise_tukeyhsd

tukey = pairwise_tukeyhsd(endog=df_melt["value"],
                          groups=df_melt["treatments"], alpha=0.05)
print(tukey.summary())

Each row of the output lists a pair of treatments, the mean difference, the adjusted p-value, the confidence interval, and a column reject. A value of True means the pair differs significantly. Agricultural studies in Indonesia often use Duncan’s multiple range test instead; Tukey’s test is more conservative and more widely accepted in international journals.

Checking the assumptions

One-way ANOVA assumes three conditions: (1) observations are independent; (2) residuals are approximately normal within each group; and (3) group variances are equal. The second and third assumptions can be tested in Python.

print(stats.shapiro(model.resid))                          # normality
print(stats.levene(df["A"], df["B"], df["C"], df["D"]))    # equal variances

A p-value above 0.05 in both tests supports the assumptions. When variances differ, Welch’s ANOVA is a safer alternative; when normality fails badly with small samples, the Kruskal-Wallis test (stats.kruskal) offers a nonparametric option.

What if the assumptions are not met?

Two alternatives cover most situations. When the residuals are approximately normal but the variances differ between groups (Levene’s test p < 0.05), Welch’s ANOVA is the appropriate test, since it does not assume equal variances. When the residuals are clearly non-normal and the sample per group is small, the Kruskal-Wallis test compares the groups based on ranks.

import pingouin as pg
from scipy import stats

# Welch's ANOVA (unequal variances)
print(pg.welch_anova(data=df_long, dv="yield", between="treatment"))

# Games-Howell post hoc, paired with Welch's ANOVA
print(pg.pairwise_gameshowell(data=df_long, dv="yield", between="treatment"))

# Kruskal-Wallis (rank-based)
groups = [g["yield"].values for _, g in df_long.groupby("treatment")]
print(stats.kruskal(*groups))

Welch’s ANOVA is followed by the Games-Howell post hoc test, while the Kruskal-Wallis test is followed by Dunn’s test with a correction for multiple comparisons. Thus, each alternative has its own matching post hoc procedure, and mixing them (for example Kruskal-Wallis followed by Tukey HSD) should be avoided.

How large is the effect?

A significant F-test indicates that at least one mean differs, yet it does not show how large the difference is. Eta squared (η² = SStreatment / SStotal) expresses the proportion of variance explained by the treatment. Common benchmarks treat 0.01 as small, 0.06 as medium, and 0.14 as large. Because η² is slightly biased upward in small samples, omega squared (ω²) is often preferred in publications. The pg.anova(..., detailed=True) function in pingouin reports both the F-test and the effect size in one table.

The importance of effect size becomes clear in a simple greenhouse scene. A student compares three organic fertilizers on 30 pots of chili and obtains p = 0.04. The supervisor asks how much the yield actually changed. The answer, η² = 0.21 with a 14% yield difference between the best and the worst treatment, turns a bare p-value into a statement that a farmer can understand.

How to report one-way ANOVA results

A complete report contains the test, degrees of freedom, F-value, p-value, effect size, and the post hoc result. For example: “Fertilizer type had a significant effect on fruit yield (F(2, 27) = 7.31; p = 0.003; η² = 0.35). Tukey’s HSD test showed that treatment B produced a higher yield than the control (mean difference 0.42 kg/plant; p = 0.002), whereas treatments A and B did not differ (p = 0.41).” Consequently, the reader obtains both the statistical decision and its practical meaning.

Related guides on Catatan Budi: CRD vs RCBD, Heteroscedasticity: detection and fixes, R-squared vs adjusted vs predicted R-squared.

Frequently asked questions

Which Python function performs one-way ANOVA?

scipy.stats.f_oneway returns the F-statistic and p-value. statsmodels.stats.anova_lm produces the complete ANOVA table.

What should be done after a significant ANOVA?

A post hoc test such as Tukey’s HSD or Duncan’s test identifies which group pairs differ. Without a significant F-test, post hoc tests are not needed.

Can one-way ANOVA be used for only two groups?

Yes, and the result equals an independent t-test, with F equal to t squared. For two groups, the t-test is the usual choice.

What is the difference between one-way and two-way ANOVA?

One-way ANOVA has one factor. Two-way ANOVA has two factors and can test their interaction, for example fertilizer dose and plant variety.

Is Python accepted for ANOVA in a thesis?

Yes. scipy and statsmodels are established open-source libraries; the report should state the package versions and the tests used.

How many replications per group are needed for one-way ANOVA?

A practical minimum is three replications per group, so that the variance within each group can be estimated. However, power analysis is the better guide: detecting a medium effect (f = 0.25) with three groups, α = 0.05, and power of 0.80 requires about 53 observations per group, while a large effect (f = 0.40) requires about 21 per group.

Does the order of groups matter in the analysis?

No. One-way ANOVA treats the groups as unordered categories, so changing their order does not change the F-value. When the groups represent increasing doses, such as 0, 50, 100, and 150 kg of fertilizer, a regression or polynomial contrast often provides more information than a post hoc comparison of every pair.

Can unequal group sizes be analyzed?

Yes. The F-test handles unequal group sizes, and Tukey’s HSD becomes the Tukey-Kramer procedure automatically in statsmodels. However, unequal sizes make the test more sensitive to unequal variances, which is another reason to check Levene’s test first.

What is the difference between Tukey HSD and the Duncan test?

Both compare every pair of means after a significant ANOVA. Tukey HSD controls the familywise error rate for all comparisons and is therefore more conservative, whereas the Duncan multiple range test is more liberal and detects differences more easily. Agricultural journals still accept Duncan in many countries, yet Tukey HSD is the safer choice for international publication. Whichever test is chosen, the method section should name it explicitly so that the result can be reproduced.

References

  • Montgomery, D. C. (2017). Design and Analysis of Experiments (9th ed.). Wiley.
  • Seabold, S., and Perktold, J. (2010). Statsmodels: Econometric and statistical modeling with Python. Proceedings of the 9th Python in Science Conference, 92–96.
  • Virtanen, P., et al. (2020). SciPy 1.0: Fundamental algorithms for scientific computing in Python. Nature Methods, 17, 261–272.

How to cite this article: Agung Budi Santoso (2026). One-Way ANOVA in Python: F-Test, Tukey Post Hoc, and Assumptions. Catatan Budi. https://agungbudisantoso.com/en/one-way-anova-python/

Photo of Agung Budi Santoso

Written by

Agung Budi Santoso

Lecturer in Management & Agribusiness · Universitas Sumatera Utara

A lecturer and researcher who turns statistics, econometrics, and agribusiness research methods into practical, step-by-step notes for students and researchers.

Discussion

No comments yet. Have a question about this topic? Write it below and I will do my best to answer.

Leave a comment

Your email address will not be published.