I have a formula as a text that is generated on the fly (dynamic)
formula = "(-500) 7.7* df['A'] -0.1234 * df['B']"
the formula is a text string and it is configured at run time, but it will always have dependency on existing other fields.
I would like to use this formaul to create a new field df['calculated'] that is based on this formula.
I looked at panada.apply(), map(), assign(), but I still can't get it to work.
Please advise if there a way to do this.
Thank you
CodePudding user response:
Using pd.assign and eval
formula = "(-500) 7.7 * df['A'] -0.1234 * df['B']"
df = df.assign(calculated=eval(formula))