Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average the duplicated values from two paired lists in Python

Tags:

python

list

in my code I obtain two different lists from different sources, but I know they are in the same order. The first list ("names") contains a list of keys strings, while the second ("result_values") is a series of floats. I need to make the pair unique, but I can't use a dictionary as only the last value inserted would be kept: instead, I need to make an average (arithmetic mean) of the values that have a duplicate key.

Example of the wanted results:

names = ["pears", "apples", "pears", "bananas", "pears"]
result_values = [2, 1, 4, 8, 6] # ints here but it's the same conceptually

combined_result = average_duplicates(names, result_values)

print combined_result

{"pears": 4, "apples": 1, "bananas": 8}

My only ideas involve multiple iterations and so far have been ugly... is there an elegant solution to this problem?

like image 742
Einar Avatar asked Aug 06 '26 03:08

Einar


2 Answers

from collections import defaultdict
def averages(names, values):
    # Group the items by name.
    value_lists = defaultdict(list)
    for name, value in zip(names, values):
        value_lists[name].append(value)

    # Take the average of each list.
    result = {}
    for name, values in value_lists.iteritems():
        result[name] = sum(values) / float(len(values))
    return result

names = ["pears", "apples", "pears", "bananas", "pears"]
result_values = [2, 1, 4, 8, 6]
print averages(names, result_values)
like image 144
Glenn Maynard Avatar answered Aug 08 '26 16:08

Glenn Maynard


I would use a dictionary anyways

averages = {}
counts = {}
for name, value in zip(names, result_values):
    if name in averages:
        averages[name] += value
        counts[name] += 1
    else:
        averages[name] = value
        counts[name] = 1
for name in averages:
    averages[name] = averages[name]/float(counts[name]) 

If you're concerned with large lists, then I would replace zip with izip from itertools.

like image 23
aaronasterling Avatar answered Aug 08 '26 16:08

aaronasterling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!