Following on from https://stackoverflow.com/a/30825549/1021819, first split the list into a chunked list-of-lists:
NaN=None # or np.nan, float('nan'), 'nan' or any other separator value you like = even '/'
my_list = [NaN, 5, 6, 7, NaN, NaN, NaN, 6, 2, 8, 5, 4, NaN, NaN]
from itertools import groupby
chunks = list(list(g) for k,g in groupby(my_list, key=lambda x: x is not NaN) if k))
# [[5, 6, 7], [6, 2, 8, 5, 4]]
Then you can use the built-in statistics.mean()
as follows:
import statistics
output = [statistics.mean(chunk) for chunk in chunks]
# [6, 5]
There you go.
Notes:
- No need for
numpy
. But if you do want a pure numpy
solution you can use https://stackoverflow.com/a/31863171/1021819
- Don't use
list
for your variable name since it is the name of a built-in type!