Home > other >  How to average numeric values across multiple lists in a dictionary?
How to average numeric values across multiple lists in a dictionary?

Time:11-11

I created the following dictionary that includes multiple key-value pairs. The values are lists containing numbers.

PLE_dict = {
        "Task_1": [1, 2, 8],
        "Task_2": [5, 1, 9],
        "Task_3": [1, 1, 3],
        "Task_4": [5, 3 ,5],
        }

I also have an empty list: Task_mean = []

My aim is to compute the averages across the four lists’ "columns" in the dictionary PLE_dict to subsequently insert them into the list Task_mean. More precisely, each new value in Task_mean should correspond to the mean or average across each "column" so to speak in the dictionary.

The result would look as follows: Task_mean = [3, 1.75, 6.25]

I tried something along the following lines, but I am stuck:

 for key, item in PLE_dict.items():
        mean_column = np.mean(item[0])

CodePudding user response:

Here is one solution with zip, sum and len which are builtin functions in python.

>>> PLE_dict = {
...         "Task_1": [1, 2, 8],
...         "Task_2": [5, 1, 9],
...         "Task_3": [1, 1, 3],
...         "Task_4": [5, 3 ,5],
...         }
>>> 
>>> [sum(lst) / len(lst) for lst in zip(*PLE_dict.values())]
[3.0, 1.75, 6.25]

CodePudding user response:

You can use pandas.

import pandas as pd

PLE_dict = {
        "Task_1": [1, 2, 8],
        "Task_2": [5, 1, 9],
        "Task_3": [1, 1, 3],
        "Task_4": [5, 3 ,5],
        }

df = pd.DataFrame(PLE_dict)
Task_mean = df.mean(axis=1).to_list()
# [3.0, 1.75, 6.25]
  • Related