Open In App

How to Perform Bartlett’s Test in Python?

Improve
Improve
Like Article
Like
Save
Share
Report

Bartlett’s test is used to check whether all samples have the same variance. it’s also called Bartlett’s test for homogeneity. Before executing some statistical tests like the One-Way ANOVA, Barlett’s test ensures that the hypothesis of equal variances is correct. It’s utilized when your data is almost certainly from a Gaussian distribution or normal distribution.

There is a considerable variation in variances if the Bartlett test statistic is bigger than this critical value. There is no significant difference if the Bartlett test statistic is smaller than this critical value.

This is a hypotheses test and the two hypotheses are as follows:

  • null hypothesis: the groups have equal variance.
  • Alternative hypothesis: one group has a different variance compared to the others.

If ‘n’ is the number of groups, n-1 is the degree of freedom. If the p-value is less than the level of significance (alpha value) we accept the alternative hypothesis and we reject the null hypothesis. In python Bartlett’s test is performed by using the scipy.stats.bartlett() function from scipy.stats library.

scipy.stats.bartlett() function:

syntax: scipy.stats.bartlett(*args)

args : arrays of samples

Returns

  • statistic – float value
  • pvalue – p value of the test

Example:

In this example, we import the necessary packages, read the CSV file. there are three species in the dataset and we need the sepal_length of each species for performing Bartlett’s test to check whether they have equal variances and if they come out from populations having the same variance. the method returns test_statistic and p-value.

To view and download the CSV file used click here.

Python3




# importing packages and modules
import pandas as pd
import scipy.stats as stats
  
# reading CSV file
dataset = pd.read_csv('iris.csv')
  
# data which contains sepal width of the three species
data = [dataset[dataset['species'] == "setosa"]['sepal_length'],
        dataset[dataset['species'] == "versicolor"]['sepal_length'],
        dataset[dataset['species'] == "virginica"]['sepal_length']]
  
# performing Bartlett's test
test_statistic, p_value = stats.bartlett(data[0], data[1], data[2])
  
print(test_statistic, p_value)


Output:

16.005701874401502 0.0003345076070163035

If we consider the level of significance of alpha value to be 0.05 then we can clearly see that p-value is less than 0.05. so, our null hypothesis is rejected and an alternative hypothesis is taken. the groups do not have equal variance and they might come out from different populations. One assumption of one-way ANOVA is that the groups should have equal variances but as it’s contradicting in this example we can come to a conclusion that one-way ANOVA should not be performed. 


Last Updated : 21 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads