Average Of Elements In A List Of List Grouped By First Item In The List
My list looks like my_list = [['A', 6, 7], ['A', 4, 8], ['B', 9, 3], ['C', 1, 1]], ['B', 10, 7]] I want to find the averages of the other two columns in each of the inner lists gro
Solution 1:
Assuming you meant to use the following list:
In [4]: my_list = [['A', 6, 7], ['A', 4, 8], ['B', 9, 3], ['C', 1, 1], ['B', 10, 7]]
The simply use a defaultdict
to group by the first element, then find the mean
:
In [6]: from collections import defaultdict
In [7]: grouper = defaultdict(list)
In [8]: for k, *tail in my_list:
...: grouper[k].append(tail)
...:
In [9]: grouper
Out[9]:
defaultdict(list,
{'A': [[6, 7], [4, 8]], 'B': [[9, 3], [10, 7]], 'C': [[1, 1]]})
In [10]: import statistics
In [11]: {k: list(map(statistics.mean, zip(*v))) for k,v in grouper.items()}
Out[11]: {'A': [5, 7.5], 'B': [9.5, 5], 'C': [1, 1]}
Note, if you are on Python 2, no need to call list
after map
. Also, you should use iteritems
instead of items
.
Also, you will have to do something like:
forsubin my_list:
grouper[sub[0]].append(sub[1:])
Instead of the cleaner version on Python 3.
Finally, there is no statistics
module in Python 2. So just do:
def mean(seq):
returnfloat(sum(seq))/len(seq)
and use that mean
instead of statistics.mean
Solution 2:
Similarly using itertools.groupby
importoperatoras op
import itertools as it
import statistics as stats
iterables = [['A', 6, 7], ['A', 4, 8], ['B', 9, 3], ['C', 1, 1], ['B', 10, 7]]
groups = it.groupby(sorted(iterables), op.itemgetter(0))
{k: list(map(stats.mean, zip(*[i[1:] for i in g]))) for k, g in groups}
# {'A': [5, 7.5], 'B': [9.5, 5], 'C': [1, 1]}
Post a Comment for "Average Of Elements In A List Of List Grouped By First Item In The List"