Home > Back-end >  How to calculate the mean of elements of a lists inside a dictionary in python?
How to calculate the mean of elements of a lists inside a dictionary in python?

Time:10-15

Hi I have a dict in python that looks like that:

{{'NN3-001': {'diffe_1':[1,2,3,4]},{'mas_1':[10,20,30,40]},{'diffe_2':[5,6,7,8]},{'mas_2':[50,60,70,80]}},
{'NN3-002': {'diffe_1':[14,15,16,17]},{'mas_1':[100,200,300,400]},{'diffe_2':[18,19,20,21]},{'mas_2':[500,600,700,800]}}}

Where NN3-X is the id of the time series, and diff and mas are the name of the models and the numbers after the _ are the times that the model was executed.

And I would like to have the mean of each i element of the list corresponding with i element of the other list, that have the same name of the model,for example: 1, of diffe_1, plus 5, from diffe_2, the mean would be 3, and the final product would something like:

{{'NN3-001': {'diffe':[3,4,5,6]}, {'mas':[30,40,50,60]}},
{'NN3-002': {'diffe':[16,17,18,19]}, {'mas':[300,400,500,600]}}}

Thanks.

CodePudding user response:

First, yeah, your dictionary isn't valid, but that's probably because you wrote it on just two lines. You probably want to write it this way:

dictionary = {
    'NN3-001': {
        'diffe_1':[1,2,3,4],
        'mas_1':[10,20,30,40],
        'diffe_2':[5,6,7,8],
        'mas_2':[50,60,70,80],
        },
    'NN3-002': {
        'diffe_1':[14,15,16,17],
        'mas_1':[100,200,300,400],
        'diffe_2':[18,19,20,21],
        'mas_2':[500,600,700,800],
        },
    }

And for the mean-computing function:

def compute_mean(dictionary):
    new_dictionary = {}
    # Loop on 'NN3-' level
    for key, sub_dictionary in dictionary.items():
        new_sub_dictionary, accumulated_arrays = {}, {}
        # Loop on 'diffe_' level
        for sub_key, list in sub_dictionary.items():
            # Extract the sub_key without the _n
            sub_key = sub_key.split('_')[0]
            # If we already encountered this sub_key
            if sub_key in new_sub_dictionary:
                new_sub_dictionary[sub_key]  = np.array(list)
                accumulated_arrays[sub_key]  = 1
            # If we haven't encountered this sub_key
            else:
                new_sub_dictionary[sub_key] = np.array(list)
                accumulated_arrays[sub_key] = 0
        # Compute mean and convert back to list 
        for sub_key, array in new_sub_dictionary.items():
            new_sub_dictionary[sub_key] = list(array / accumulated_arrays[sub_key])
        # Add to the main dictionary
        new_dictionary[key] = new_sub_dictionary
    return new_dictionary

CodePudding user response:

First: your example is not correct dictionary. You missed {} in some places.

You should have

{
    'NN3-001': {'diffe_1':[1,2,3,4],'mas_1':[10,20,30,40],'diffe_2':[5,6,7,8],'mas_2':[50,60,70,80]},
    'NN3-002': {'diffe_1':[14,15,16,17],'mas_1':[100,200,300,400],'diffe_2':[18,19,20,21],'mas_2':[500,600,700,800]}
}

To get single list you can use

values = data['NN3-001']['diffe_1'] 

and you can calculate mean

mean = sum(values)/len(values)

For all list you have to use for-loops with dict.items()

dictionary = {
    'NN3-001': {'diffe_1':[1,2,3,4],'mas_1':[10,20,30,40],'diffe_2':[5,6,7,8],'mas_2':[50,60,70,80]},
    'NN3-002': {'diffe_1':[14,15,16,17],'mas_1':[100,200,300,400],'diffe_2':[18,19,20,21],'mas_2':[500,600,700,800]}
}

for name, values in dictionary.items():
    print('=== time serie:', name, '===')
    for key, data in values.items():
        print('  key:', key)
        print(' data:', data)
        print(' mean:', sum(data)/len(data))
        print('---')

Result:

=== time serie: NN3-001 ===
  key: diffe_1
 data: [1, 2, 3, 4]
 mean: 2.5
---
  key: mas_1
 data: [10, 20, 30, 40]
 mean: 25.0
---
  key: diffe_2
 data: [5, 6, 7, 8]
 mean: 6.5
---
  key: mas_2
 data: [50, 60, 70, 80]
 mean: 65.0
---
=== time serie: NN3-002 ===
  key: diffe_1
 data: [14, 15, 16, 17]
 mean: 15.5
---
  key: mas_1
 data: [100, 200, 300, 400]
 mean: 250.0
---
  key: diffe_2
 data: [18, 19, 20, 21]
 mean: 19.5
---
  key: mas_2
 data: [500, 600, 700, 800]
 mean: 650.0

EDIT:

After changes in question I see that you need zip(diffe_1, diffe_2) to create pairs.

dictionary = {
    'NN3-001': {'diffe_1':[1,2,3,4],'mas_1':[10,20,30,40],'diffe_2':[5,6,7,8],'mas_2':[50,60,70,80]},
    'NN3-002': {'diffe_1':[14,15,16,17],'mas_1':[100,200,300,400],'diffe_2':[18,19,20,21],'mas_2':[500,600,700,800]}
}

result = {}

for name, values in dictionary.items():
    print('=== time serie:', name, '===')
    
    result[name] = {'diff':[], 'mas':[]}
    
    print('--- diffe_1, diffe_2 ---')
    for a, b in zip(values['diffe_1'],values['diffe_2']):
        mean = int( (a b)/2 )
        print(a, '&', b, '=>', mean)
        result[name]['diff'].append(mean)
        
    print('--- mas_1, mas_2 ---')
    for a, b in zip(values['mas_1'],values['mas_2']):
        mean = int( (a b)/2 )
        print(a, '&', b, '=>', mean)
        result[name]['mas'].append(mean)

print(result)      

gives

=== time serie: NN3-001 ===
--- diffe_1, diffe_2 ---
1 & 5 => 3.0
2 & 6 => 4.0
3 & 7 => 5.0
4 & 8 => 6.0
--- mas_1, mas_2 ---
10 & 50 => 30.0
20 & 60 => 40.0
30 & 70 => 50.0
40 & 80 => 60.0
=== time serie: NN3-002 ===
--- diffe_1, diffe_2 ---
14 & 18 => 16.0
15 & 19 => 17.0
16 & 20 => 18.0
17 & 21 => 19.0
--- mas_1, mas_2 ---
100 & 500 => 300.0
200 & 600 => 400.0
300 & 700 => 500.0
400 & 800 => 600.0


{
'NN3-001': {'diff': [3, 4, 5, 6], 'mas': [30, 40, 50, 60]},  
'NN3-002': {'diff': [16, 17, 18, 19], 'mas': [300, 400, 500, 600]}
}

You may also use loop for prefix in ['diffe', 'mas']: to reduce code.

dictionary = {
    'NN3-001': {'diffe_1':[1,2,3,4],'mas_1':[10,20,30,40],'diffe_2':[5,6,7,8],'mas_2':[50,60,70,80]},
    'NN3-002': {'diffe_1':[14,15,16,17],'mas_1':[100,200,300,400],'diffe_2':[18,19,20,21],'mas_2':[500,600,700,800]}
}

result = {}

for name, values in dictionary.items():
    print('=== time serie:', name, '===')
    
    
    result[name] = {}
    
    for prefix in ['diffe', 'mas']:

        print('--- prefix:', prefix, '---')
        
        result[name][prefix] = []

        for a, b in zip(values[prefix '_1'],values[prefix '_2']):
            mean = int( (a b)/2 )
            print(a, '&', b, '=>', mean)
            result[name][prefix].append(mean)
        
print(result)
  • Related