Allie H Allie H - 1 month ago 12
Python Question

Python - appending to multiple arrays

If I wanted to perform something like Levene's test of equal variances via scipy stats, which produces two outputs (the test statistic and p-value) for all the data in a dictionary, how would I append the outputs for each test to two different lists? I tried the code below:

test_stat[]
p_value[]
for i in range(0, n_data):
for j in range(1, n_name):
test_stat[i], p_value[i] = scipy.stats.levene(data[i][name[j-1]],
data[i][name[j]],
center='median')


But this clearly isn't the way to go about it, as I keep getting an
IndexError
because the list assignment index out of range.

Any suggestions would be greatly appreciated. Thanks!

Answer

Not everything needs to be in a single line... This should work fine:

test_stats = []
p_values = []
for i in range(0, n_data):
    for j in range(1, n_name):
        test_stat, p_value = scipy.stats.levene(data[i][name[j-1]], 
                                                data[i][name[j]], 
                                                center='median')
        test_stats.append(test_stat)
        p_values.append(p_value)

Though of course this will add n_data * n_name rows.

Comments