0

I have a series of column with numbers to put into different formulas (in my example I use only sum and product). And the final column should give me the result of the formula (I get "None" instead). In my example, if it is written "2 + 1" I would simply like to have 3 as result of my operation

Can you suggest me the right solution please ?

import pandas as pd
operation = ["+", "*", "+", "*"]
op_number = ["Op1", "Op2", "Op3", "Op4"]
number_1 =[1,3,5,6] 
number_2 =[2,4,2,3] 
operation = pd.Series(operation)
op_number = pd.Series(op_number)
number_1 = pd.Series(number_1)
number_2 = pd.Series(number_2)
frame = { 'operation': operation, 'op_number': op_number,
         'number_1' : number_1, 'number_2':number_2}    
s1 = pd.DataFrame(frame)
s1['derived'] =  s1['number_1'].astype(str)   + " " + s1['operation'] + " " + s1['number_2'].astype(str)  
s1['result'] = s1['derived'].apply(lambda x : exec(x) )
s1
manuzzo
  • 73
  • 3

1 Answers1

0

I would not recommend using pandas for this. However, if you want the solution in pandas then here is it:

You are doing exec() which works well but it always returns None. Hence, replace exec() with eval(). Here's your updated code:

import pandas as pd
operation = ["+", "*", "+", "*"]
op_number = ["Op1", "Op2", "Op3", "Op4"]
number_1 =[1,3,5,6] 
number_2 =[2,4,2,3] 
operation = pd.Series(operation)
op_number = pd.Series(op_number)
number_1 = pd.Series(number_1)
number_2 = pd.Series(number_2)
frame = { 'operation': operation, 'op_number': op_number,
         'number_1' : number_1, 'number_2':number_2}    
s1 = pd.DataFrame(frame)
s1['derived'] =  s1['number_1'].astype(str)   + " " + s1['operation'] + " " + s1['number_2'].astype(str)  
s1['result'] = s1['derived'].apply(lambda x : eval(x) )
print(s1)

Thanks to @MaxShawabkeh

The Myth
  • 1,090
  • 1
  • 4
  • 16