Home > OS >  Calculate the mean and variance by element by element of multiple arrays in Python
Calculate the mean and variance by element by element of multiple arrays in Python

Time:12-08

I have a block of code that provides five arrays:

for i in range(5):
    x = pic[10,15 i]

This produces the following five arrays:

[22 23 20 ...   32   45    0]
[25 23 20 ...   33   39    0]
[26 23 26 ...   31   56    0]
[28 23 26 ...    0   11    0]
[25 34 25 ...    0    0    0]

I want to calculate the mean of those five arrays by element by element. So, I want a final output like this:

[25.2 25.2 23.4 ... 19.2 30.2 0]  

The first element of the output array (25.2) is generated by (22 25 26 28 25)/5. I am not getting how to do it in Python. Any help would be highly appreciated. Also, if you can help me calculate the variance as well it would be an amazing help!

CodePudding user response:

Using zip function:-

Code:-

import statistics
#Using package statistics :- Variance
#Using Zip function -: mean
lis=[[22,23,20,32,45,0],
     [25,23,20,33,39,0],
     [26,23,26,31,56,0],
     [28,23,26,0,11,0],
     [25,34,25,0,0,0]]
mean=[]
variance=[]
for i in zip(*lis):
    mean.append(sum(i)/len(i))
    variance.append(statistics.variance(i))
print(mean)
print(variance)

Output:-

[25.2, 25.2, 23.4, 19.2, 30.2, 0.0]
[4.7, 24.2, 9.8, 307.7, 560.7, 0]

CodePudding user response:

You could use numpy as following: Create an array that stores the 5 arrays, and then use the numpy.mean() function:

import numpy as np

arrays = [
[22, 23, 20, 32, 45, 0],
[25, 23, 20, 33, 39, 0],
[26, 23, 26, 31, 56, 0],
[28, 23, 26, 0, 11, 0],
[25, 34, 25, 0, 0, 0]]

mean = np.mean(arrays, axis=0)
variance = np.variance(arrays, axis=0)

The axis specifies that you want to calculate the mean column wise and not row wise.

  • Related