Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mean value of each element in multiple lists - Python

If I have two lists

a = [2,5,1,9]
b = [4,9,5,10]

How can I find the mean value of each element, so that the resultant list would be:

[3,7,3,9.5]
like image 460
ryansin Avatar asked Apr 16 '17 10:04

ryansin


3 Answers

Referring to your title of the question, you can achieve this simply with:

import numpy as np

multiple_lists = [[2,5,1,9], [4,9,5,10]]
arrays = [np.array(x) for x in multiple_lists]
[np.mean(k) for k in zip(*arrays)]

Above script will handle multiple lists not just two. If you want to compare the performance of two approaches try:

%%time
import random
import statistics

random.seed(33)
multiple_list = []
for seed in random.sample(range(100), 100):
    random.seed(seed)
    multiple_list.append(random.sample(range(100), 100))

result = [statistics.mean(k) for k in zip(*multiple_list)]

or alternatively:

%%time
import random
import numpy as np

random.seed(33)
multiple_list = []
for seed in random.sample(range(100), 100):
    random.seed(seed)
    multiple_list.append(np.array(random.sample(range(100), 100)))

result = [np.mean(k) for k in zip(*multiple_list)]

To my experience numpy approach is much faster.

like image 70
nimbous Avatar answered Oct 01 '22 12:10

nimbous


What you want is the mean of two arrays (or vectors in math).

Since Python 3.4, there is a statistics module which provides a mean() function:

statistics.mean(data)

Return the sample arithmetic mean of data, a sequence or iterator of real-valued numbers.

You can use it like this:

import statistics

a = [2, 5, 1, 9]
b = [4, 9, 5, 10]

result = [statistics.mean(k) for k in zip(a, b)]
# -> [3.0, 7.0, 3.0, 9.5]

notice: this solution can be use for more than two arrays, because zip() can have multiple parameters.

like image 22
Laurent LAPORTE Avatar answered Oct 01 '22 11:10

Laurent LAPORTE


>>> a = [2,5,1,9]
>>> b = [4,9,5,10]
>>> [(g + h) / 2 for g, h in zip(a, b)]
[3.0, 7.0, 3.0, 9.5]
like image 42
Uriel Avatar answered Oct 01 '22 12:10

Uriel