Python: Group same integer values, then average

Viewed 203

I have a huge array of data and I would like to do subgroups for the values for same integers and then take their average.

For example:

a = [0, 0.5, 1, 1.5, 2, 2.5]

I want to take sub groups as follows:

[0, 0.5] [1, 1.5] [2, 2.5]

... and then take the average and put all the averages in a new array.

4 Answers

Assuming you want to group by the number's integer value (so the number rounded down), something like this could work:

>>> a = [0, 0.5, 1, 1.5, 2, 2.5]
>>> groups = [list(g) for _, g in itertools.groupby(a, int)]
>>> groups
[[0, 0.5], [1, 1.5], [2, 2.5]]

Then averaging becomes:

>>> [sum(grp) / len(grp) for grp in groups]
[0.25, 1.25, 2.25]

This assumes a is already sorted, as in your example.

Ref: itertools.groupby, list comprehensions.

If you have no problem using additional libraries:

import pandas as pd
import numpy as np

a = [0, 0.5, 1, 1.5, 2, 2.5]
print(pd.Series(a).groupby(np.array(a, dtype=np.int32)).mean())

Gives:

0    0.25
1    1.25
2    2.25
dtype: float64

You can use groupby to easily get that (you might need to sort the list first):

from itertools import groupby
from statistics import mean

a = [0, 0.5, 1, 1.5, 2, 2.5]
for k, group in groupby(a, key=int):
    print(mean(group))

Will give:

0.25
1.25
2.25

If you want an approach with dictionary, you can go ahead like this:

dic={}
a = [0, 0.5, 1, 1.5, 2, 2.5]
for items in a:
    if int(items) not in dic:
        dic[int(items)]=[]
    dic[int(items)].append(items)
print(dic)

for items in dic:
    dic[items]=sum(dic[items])/len(dic[items])
print(dic)
Related