Implementing a recursive function to execute layered calculations

29 views Asked by At

Apologies for the butchered title.

I have a db of metrics where I have fields like Metric Title, Metric ID, Metric Abbreviation, and Metric Formula. The Metric Formula indicates if the metric requires other metrics to be calculated. For example:

Metric Title Metric ID Metric Abbreviation Metric Formula
MetricA 234 MA
MetricB 567 MB
MetricC 452 MC MA+MB
MetricD 123 MD MC*MA

I am trying to implement a recursive function that evaluates if the metric formula is not empty to use the abbreviations in the formula to then evaluate those row's formula field and so on and so on. Once it's at the root node, ie a row where the metric formula is empty get a value and go back up one level. Could someone please point me in the right direction for researching this type of algorithm?

1

There are 1 answers

0
mozway On

If I understand correctly and you want to evaluate the formulas, you could take advantage of pandas.eval. Build a dictionary of abbreviations:ID, and pass it to eval as a local_dict:

d = df.set_index('Metric Abbreviation')['Metric ID'].to_dict()

m = df['Metric Formula'].notna()
df.loc[m, 'Result'] = (df.loc[m, 'Metric Formula']
                         .apply(pd.eval, local_dict=d)
                      )

Output:

  Metric Title  Metric ID Metric Abbreviation Metric Formula    Result
0      MetricA        234                  MA           None       NaN
1      MetricB        567                  MB           None       NaN
2      MetricC        452                  MC          MA+MB     801.0
3      MetricD        123                  MD          MC*MA  105768.0