I know this is a bad one. I really want to know if this is possible to do in python so I have two strings with arithmetic equation now I want to place them inside a df[ ]. df is a data frame Is this possible to do?
X = "'cars'+'bikes'*'planes'"
Now this should be placed like this below
X = df['cars']+df['bikes']*df['planes']
If possible how to do it?
I am assuming that you know the consequences of using eval
.
s = "'cars'+'bikes'*'planes'"
df['out'] = eval(re.sub(r"([^+\-*\/]+)", r'df[\1]', s))
What is does is basically substitutes df
. It changes 'cars'+'bikes'*'planes'
to df['cars']+df['bikes']*df['planes']
.
If you don't want to use eval
you can parse the column names
and operands
like
columns = re.findall(r"'([^+\-*\/]+)'", s)
operands = re.findall(r'([+\-*\/]+)', s)
But in this case, you need to define operate precedence and create a tree to calculate the result.
import re
import pandas as pd
s = "'cars'+30*'bikes'-'planes'+20"
s2 = re.sub(r"('[^+\-*\/'\d]+')", r'df[\1]', s)
pd.eval(s2)