Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python mean of list of lists

I want to find the means of all the negative numbers from a list that has a mix of positive and negative numbers. I can find the mean of the lists as

import numpy as np

listA = [ [2,3,-7,-4] , [-2,3,4,-5] , [-5,-6,-8,2] , [9,5,13,2]  ]
listofmeans = [np.mean(i) for i in listA ]

I want to create a similar one line code that only takes the mean of the negative numbers in the list. So for example the first element of the new list would be (-7 + -4)/2 = -5.5

My complete list would be:

listofnegativemeans = [ -5.5, -3.5, -6.333333, 0 ] 
like image 901
piccolo Avatar asked Mar 01 '16 16:03

piccolo


People also ask

How do you do mean of a list in Python?

To find the average of the numbers in a list in Python, we have multiple ways. The two main ways are using the Len() and Sum() in-built function and using the mean() function from the statistics module.

How do you find the mean of a list of values?

The goal here is to find the average/mean of a list of numbers. The average is the sum of all the numbers in a list divided by its length.

How do you average two lists in Python?

Method #1 : Using sum() + len() + “+” operator The average value can be determined by the conventional sum() and len function of python and the extension of one to two lists can be dealt using the “+” operator.

What does list [:] mean in Python?

A list is an ordered and mutable Python container, being one of the most common data structures in Python. To create a list, the elements are placed inside square brackets ([]), separated by commas. As shown above, lists can contain elements of different types as well as duplicated elements.


2 Answers

You could use the following:

listA = [[2,3,-7,-4], [-2,3,4,-5], [-5,-6,-8,2], [9,5,13,2]]
means = [np.mean([el for el in sublist if el < 0] or 0) for sublist in listA]
print(means)

Output

[-5.5, -3.5, -6.3333, 0.0]

If none of the elements in sublist are less than 0, the list comprehension will evaluate to []. By including the expression [] or 0 we handle your scenario where you want to evaluate the mean of an empty list to be 0.

like image 164
gtlambert Avatar answered Sep 18 '22 11:09

gtlambert


If you're using numpy at all, you should strive for numpythonic code rather than falling back to python logic. That means using numpy's ndarray data structure, and the usual indexing style for arrays, rather than python loops.

For the usual means:

>>> listA
[[2, 3, -7, -4], [-2, 3, 4, -5], [-5, -6, -8, 2], [9, 5, 13, 2]]
>>> A = np.array(listA)
>>> np.mean(A, axis=1)
array([-1.5 ,  0.  , -4.25,  7.25])

Negative means:

>>> [np.mean(row[row<0]) for row in A]
[-5.5, -3.5, -6.333333333333333, nan]
like image 27
wim Avatar answered Sep 21 '22 11:09

wim