Ykwk
Ykwk

Reputation: 39

How to average multiple lists of various lengths?

I am trying to average numbers of different lists of varying lengths. (in nested-list form as shown below)

mylist =[[1, 3, 7, 10], [3, 9, 9, 0], [5, 6]]

I want the result of

averaged_list = [3, 6, 8, 5]

I have tried,

averaged_list = [mean(x) for x in zip(*mylist)]

which only lends:

[3, 6]

mylist above is simplified just to demonstrate the purpose but it will be lengthier in practice. Thank you for the help and advice!

Upvotes: 0

Views: 73

Answers (2)

Julien
Julien

Reputation: 15071

You could do this:

from itertools import zip_longest
import numpy as np
averaged_list = [np.nanmean(x) for x in zip_longest(*mylist, fillvalue=np.nan)]

(See @michaeldel's answer for explanation, same idea)

Upvotes: 0

michaeldel
michaeldel

Reputation: 2385

zip will ignore excess values according to the shortest length iterable. You must use itertools.zip_longest instead, and must take care of filtering the None fill-values:

import itertools

averaged_list = [
    mean((x for x in xs if x is not None))  # ignore fillvalues
    for xs in itertools.zip_longest(*mylist)
]

Upvotes: 1

Related Questions