Four ways to conduct one-way ANOVA with Python

The current post will focus on how to carry out between-subjects ANOVA using Python. As mentioned in an earlier post (Repeated measures ANOVA with Python) ANOVAs are commonly used in Psychology.


We start with some brief introduction on theory of ANOVA. If you are more interested in the four methods to carry out one-way ANOVA with Python click here. ANOVA is a means of comparing the ratio of systematic variance to unsystematic variance in an experimental study. Variance in the ANOVA is partitioned in to total variance, variance due to groups, and variance due to individual differences.

Python ANOVA - theory - partitioning of the sum of squares (i.e., the variance)
Partioning of Variance in the ANOVA. SS stands for Sum of Squares.

The ratio obtained when doing this comparison is known as the F-ratio. A one-way ANOVA can be seen as a regression model with a single categorical predictor. This predictor usually has two plus categories. A one-way ANOVA has a single factor with J levels. Each level corresponds to the groups in the independent measures design.

The general form of the model, which is a regression model for a categorical factor with J levels, is:

y_i = b_0+b_1X_{1,i} +...+b_{j-1,i} + e_i

There is a more elegant way to parametrize the model. In this way the group means are represented as deviations from the grand mean by grouping their coefficients under a single term.  I will not go into detail on this equation:

y_{ij} = \mu_{grand} + \tau_j + \varepsilon_{ij}

As for all parametric tests the data need to be normally distributed (each groups data should be roughly normally distributed) for the F-statistic to be reliable. Each experimental condition should have roughly the same variance (i.e., homogeneity of variance), the observations (e.g., each group) should be independent, and the dependent variable should be measured on, at least,  an interval scale.

ANOVA using Python

In the four examples in this tutorial we are going to use the dataset “PlantGrowth” that originally was available in R but can be downloaded using this link: PlantGrowth. In the first three examples we are going to use Pandas DataFrame. All three Python ANOVA examples below are using Pandas to load data from a CSV file. Note, we can also use Pandas read excel if we have our data in an Excel file (e.g., .xlsx).

Boxplot of the different groups in our ANOVA with Python example
BoxPlot of Plantgrowth data

Judging by the Boxplot there are differences in the dried weight for the two treatments. However, easy to visually determine whether the treatments are different to the control group.

Using SciPy

We start with using SciPy and its method f_oneway from stats.

One problem with using SciPy is that  following APA guidelines we should also effect size (e.g., eta squared) as well as Degree of freedom (DF). DFs needed for the example data is easily obtained

However, if we want to calculate eta-squared we need to do some more computations. Thus, the next section will deal with how to calculate a one-way ANOVA using the Pandas DataFrame and Python code.

Calculating using Python (i.e., pure Python ANOVA)

A one-way ANOVA is quite easy to calculate so below I am going to show how to do it. First, we need  to calculate the sum of squares between (SSbetween), sum of squares within (SSwithin), and sum of squares total (SSTotal).

Sum of Squares Between

We start with calculating the Sum of Squares between. Sum of Squares Between is the variability due to interaction between the groups. Sometimes known as the Sum of Squares of the Model.

SSbetween = \frac{\sum(\sum k_i) ^2} {n} - \frac{T^2}{N}

How to Calculate Sum of Squares Within

The variability in the data due to differences within people. The calculation of Sum of Squares Within can be carried out according to this formula:

SSwithin = \sum Y^2 - \frac{\sum (\sum a_i)^2}{n}

Calculation of Sum of Squares Total

Sum of Squares Total will be needed to calculate eta-squared later. This is the total variability in the data.

SStotal = \sum Y^2 - \frac{T^2}{N}

How to Calculate Mean Square Between

Mean square between is the sum of squares within divided by degree of freedom between.

Calculation of Mean Square Within

Mean Square within is also an easy calculation;

Calculating the F-value

To reject the null hypothesis we check if the obtained F-value is above the critical value for rejecting the null hypothesis. We could look it up in a F-value table based on the DFwithin and DFbetween. However, there is a method in SciPy for obtaining a p-value.

Finally, we are also going to calculate effect size. We start with the commonly used eta-squared (η² ):

However, eta-squared is somewhat biased because it is based purely on sums of squares from the sample. No adjustment is made for the fact that what we aiming to do is to estimate the effect size in the population. Thus, we can use the less biased effect size measure Omega squared:

The results we get from both the SciPy and the above method can be reported according to APA style; F(2, 27) = 4.846, p =  .016, η² =  .264. If you want to report Omega Squared: ω2 = .204

Using Statsmodels

The third method, using Statsmodels, is also easy. We start by using ordinary least squares method and then the anova_lm method. Also, if you are familiar with R-syntax. Statsmodels have a formula api where your model is very intuitively formulated. First, we import the api and the formula api. Second we, use ordinary least squares regression with our data. The object obtained is a fitted model that we later use with the anova_lm method to obtaine a ANOVA table.

Output table:

sum_sq df F PR(>F)
group 3.76634 2 4.846088 0.01591
Residual 10.49209 27

Note, no effect sizes is calculated when we use Statsmodels.  To calculate eta squared we can use the sum of squares from the table:

Using pyvttbl anova1way

We can also use the method anova1way from the python package pyvttbl. This package also has a DataFrame method. We have to use this method instead of Pandas DataFrame to be able to carry out the one-way ANOVA.  Note, Pyvttbl is old and outdated. It requires Numpy to be at most version 1.1.x or else you will run in to an error ( “unsupported operand type(s) for +: ‘float’ and ‘NoneType’”).

This can, of course, be solved by downgrading Numpy (see my solution using a  virtual environment Step-by-step guide for solving the Pyvttbl Float and NoneType error).

Output anova1way

We get a lot of more information using the anova1way method. Maybe of particular interest here is that we get results from a post-hoc test (i.e., Tukey HSD).  Whereas the ANOVA only lets us know that there was a significant effect of treatment the post-hoc analysis reveal where this effect may be (between which groups).

That is it! In this tutorial you learned 4 methods that let you carry out one-way ANOVAs using Python. There are, of course, other ways to deal with the tests between the groups (e.g., the post-hoc analysis). One could carry out Multiple Comparisons (e.g., t-tests between each group. Just remember to correct for familywise error!) or Planned Contrasts.  In conclusion, doing ANOVAs in Python is pretty simple.

3 thoughts on “Four ways to conduct one-way ANOVA with Python

  1. Thank you for your effort, very clearly set.

    However, I am hitting a problem using ANOVA1Way, I wonder if you have any suggestions. When I make a copy of PlantGrowth.csv and type in new numbers for “weight” and then run your code, I get:

    Error: new-line character seen in unquoted field – do you need to open the file in universal-newline mode?

    Thanks and Regards

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.