0

I have been trying to evaluate math expressions in the Resolution and o_resolution columns. I have used regex to change x into * and have used the eval function to try to evaluate the expressions in the column but nothing is happening. Any suggestions?

colRes = df [['resolution', 'o_resolution']]

colRes = df[['resolution', 'o_resolution']].replace('x','*',regex=True)
colRes = df[['resolution', 'o_resolution']].apply(lambda x:eval('x'))

Resolution Column

o_resolution Column

hihi
  • 11
  • 4

1 Answers1

0

Use pandas.eval in DataFrame.applymap after replace:

d = {'resolution':['10x2','8x9','1x8'], 'o_resolution':['10x4','10x40','10x500']}
df = pd.DataFrame(d)


colRes = df [['resolution', 'o_resolution']].replace('x','*',regex=True).applymap(pd.eval)
print (colRes)
  resolution o_resolution
0         20           40
1         72          400
2          8         5000

Your solution is possible with x instead 'x', but not recommended:

colRes = df[['resolution', 'o_resolution']].replace('x','*',regex=True).applymap(lambda x:eval(x))
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252