Skip to content Skip to sidebar Skip to footer

Create A New Column Based On Calculations That Change Between Rows?

I would like to calculate a sum of variables for a given day. Each day contains a different calculation, but all the days use the variables consistently. There is a df which specif

Solution 1:

A simple suggestion, perhaps you need to rewrite a part of your code. Not sure if your want something like this:

a = 5
b = 1
c = 10# Rewrite the equation that is readable by Python# e.g. replace 3a+b by 3*a+b
data1 = [[1,"3*a+b"],
         [2,"c"],
         [3,"2*c"]]

desired_table = pd.DataFrame(data1,
                        columns=['Day','Q1'])
desired_table['Q1 solved'] = desired_table['Q1'].apply(lambda x: eval(x))
desired_table

Output:

   Day     Q1  Q1 solved
013*a+b1612      c         10232*c         20

Solution 2:

If it's possible to have the equations changed to equations with * then you could do this.

Get the mapping from the

mapping = dict(zip(conversion_table['Variable'], conversion_table['Cost'])

the eval the function and replace variables with numeric from the mapping

desired_table['Q1 solved'] = to_solve['Q1'].map(lambda x: eval(''.join([str(mapping[i]) if i.isalpha() elsestr(i) for i in x])))
0    16
1    10
2    20

Post a Comment for "Create A New Column Based On Calculations That Change Between Rows?"