python pandas assign values to column based on formula

Question:

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

Asked By: jscriptor

||

Answers:

Using pd.assign and eval

formula = "(-500) + 7.7 * df['A'] + -0.1234 * df['B']"
df = df.assign(calculated=eval(formula))
Answered By: Jason Baker
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.