Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python pandas assign values to column based on formula

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Using pd.assign and eval

formula = "(-500) + 7.7 * df['A'] + -0.1234 * df['B']"
df = df.assign(calculated=eval(formula))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading