Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write a loop function for Levene test in Python

I want to perform a Levene and one-way ANOVA test, with the outcome being continuous and a predictor with n groups. For example:

import pandas as pd
import scipy.stats as sps               

# create the df
test_df = pd.DataFrame({
    'score': [5,15,1,51,1,51,5,15,16,3,1,81,6,1,2],
    'groups': ['a','b','c','a','b','c','a','b','c','a','b','c','a','b','c']})

factor = test_df['groups'].unique()            # create a list of individual factors 
arr1 = []                                      # to store the outcome by groups
for i in range(len(factor)):
    variable = test_df[test_df['groups'] == factor[i]]['score']
                                               # Make individual values by group
    arr1.append(variable)                      # append these to arr1  
    levene = sps.levene(arr1)         # the problem is here. The code does not recognize my arr1 has multiple arrays in it.

Ideally, I would like to be able to do something like this sps.levene(arr1[0],...,arr1[n]), the loop would do the following:

  1. append each array within arr1 into a list
  2. perform one sps.levene test with the list.

Can someone please help me how to solve this issue?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to unpack the elements of arr1 when passing them to levene.
You can achieve this by using the * operator:

import pandas as pd
import scipy.stats as sps               

# create the df
test_df = pd.DataFrame({
    'score': [5,15,1,51,1,51,5,15,16,3,1,81,6,1,2],
    'groups': ['a','b','c','a','b','c','a','b','c','a','b','c','a','b','c']})

factor = test_df['groups'].unique()            # create a list of individual factors 
arr1 = []                                      # to store the outcome by groups
for i in range(len(factor)):
    variable = test_df[test_df['groups'] == factor[i]]['score']
    arr1.append(variable)                      # append these to arr1  

# Perform Levene's test
levene_result = sps.levene(*arr1)
print("Levene's test p-value:", levene_result.pvalue)

Output:

Levene's test p-value: 0.253368701021017
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading