Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate mean and min of lists with None types included

I have to calculate the mean of the following list:

j=[20, 30, 40, None, 50]

And also the min values from these nested lists which also includes the same:

x = [[20, 30, 40, None, 50], [12, 31, 43, None, 51]]

Which should return [12,30,40,50] but the following code is not working.

print(list(map(min, zip(*x))))
TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'

And for the mean I tried this:

import statistics
statistics.harmonic_mean(j)

None of them worked on this type of list.

like image 355
Abhishek Abhishek Avatar asked Oct 12 '25 05:10

Abhishek Abhishek


1 Answers

You can filter out the "None" values to get the mean and mins. For example:

from statistics import mean

data = [[20, 30, 40, None, 50], [12, 31, 43, None, 51]]

mean_val = mean(d for d in data[0] if d is not None)
print(mean_val)
# 35

min_vals = [min(a, b) for a, b in zip(*data) if a is not None and b is not None]
print(min_vals)
# [12, 30, 40, 50]
like image 85
benvc Avatar answered Oct 14 '25 18:10

benvc