Execute equation from the elements of a list in python
Question:
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?
Answers:
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
Edit
In the multiindex case it would look like this:
import pandas as pd
data = [[5, 10, 40], [2, 15, 70], [6, 14, 60]]
index = pd.MultiIndex.from_tuples([('A', 'x'), ('B', 'x'), ('C', 'y')], names=['level_1', 'level_2'])
df = pd.DataFrame(data, index=index, columns=['Value_1', 'Value_2', 'Value_3'])
lst = [5, '*', 'Value_1', '+', 'Value_3']
expression = ' '.join(str(e) for e in lst)
dresult = pd.DataFrame()
dresult['Result'] = df.eval(expression)
print(dresult)
which would give you
Result
level_1 level_2
A x 65
B x 80
C y 90
You cn then clean your df as you see fit.
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?
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
Edit
In the multiindex case it would look like this:
import pandas as pd
data = [[5, 10, 40], [2, 15, 70], [6, 14, 60]]
index = pd.MultiIndex.from_tuples([('A', 'x'), ('B', 'x'), ('C', 'y')], names=['level_1', 'level_2'])
df = pd.DataFrame(data, index=index, columns=['Value_1', 'Value_2', 'Value_3'])
lst = [5, '*', 'Value_1', '+', 'Value_3']
expression = ' '.join(str(e) for e in lst)
dresult = pd.DataFrame()
dresult['Result'] = df.eval(expression)
print(dresult)
which would give you
Result
level_1 level_2
A x 65
B x 80
C y 90
You cn then clean your df as you see fit.