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?
>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