Home > Software engineering >  How to get sum over time horizont and different names from dictionaries
How to get sum over time horizont and different names from dictionaries

Time:01-13

Let's say I have a couple of dictionaries (one per hour) which all have the same keys:

h1={'a':1, 'b':3, 'c':10}
h2={'a':7, 'b':15, 'c':2}
h3={'a':9, 'b':15, 'c':35}

How can I get the sum of absolute values between the next hours for all hours and keys, meaning a sum of the form:

|1-7| |7-9| |3-15| |15-15| |10-2| |2-35|

more generally it is something of the form:

enter image description here

where beta is 1, the psts are the keys of our dictionary and we also sum over hours.

CodePudding user response:

Probably better to use pandas than numpy for this.
Pretty sure it would just be

beta = 1
pd.DataFrame([h1, h2, h3]).diff().dropna().abs().mul(beta).sum().sum()
Out: 61.0

CodePudding user response:

Using numpy, you can craft an array, compute the absolute difference (numpy.diff abs), and sum:

h1={'a':1, 'b':3, 'c':10}
h2={'a':7, 'b':15, 'c':2}
h3={'a':9, 'b':15, 'c':35}

import numpy as np
dicts = [h1, h2, h3]

a = np.array([list(d.values()) for d in dicts])
abs(np.diff(a, axis=0)).sum()

output: 61

  •  Tags:  
  • Related