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

Execute equation from the elements of a list in python

I have the following list and dataframe:

import pandas as pd
data = [[5, 10, 40], [2, 15, 70], [6, 14, 60]]
df = pd.DataFrame(data, columns=['A', 'B', 'C'])
lst = [5, '*', 'A', '+', 'C']

And I would like to create a code to execute the equation in the lst like 5 x A + C returning the following result:

data = [[65], [80], [90]]
dresult = pd.DataFrame(data, columns=['M'])

Is that possible?

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

>Solution :

Yes. You simply do this:

import pandas as pd

data = [[5, 10, 40], [2, 15, 70], [6, 14, 60]]
df = pd.DataFrame(data, columns=['A', 'B', 'C'])
lst = [5, '*', 'A', '+', 'C']

expression = ' '.join(str(e) for e in lst)

dresult = pd.DataFrame()
dresult['M'] = df.eval(expression)

print(dresult)

which is:

   M
0  65
1  80
2  90
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