I have following pandas
DataFrame
to which I need to apply the exec
function to all the rows.
import pandas as pd
var = 2.5
df = pd.DataFrame(["var*1", "var*3", "var*5"])
The expected result I need is:
0
0 2.5
1 7.5
2 12.5
However if I do the following:
df.apply(exec)
or even:
df.apply(lambda x:exec(x))
I get the following error:
TypeError: exec() arg 1 must be a string, bytes or code object
Other option I tried was:
>>> df[0].map(lambda x:exec(x))
0 None
1 None
2 None
Name: 0, dtype: object
But it's not the result I expect.
I even tried to define a function and then apply it:
def execute(x):
exec("a = " + str(x))
return a
df[0].apply(execute)
But result is following error:
NameError: name 'var' is not defined
How can I then get the expected result?
Take a look at pandas.eval. You can reference local variables using @var
syntax.
As for arbitrary code execution, you should explicitly pass local variables as dict and use eval
to get a return value, e.g. eval("a + 2", {"a": 1})
As for your question:
df[0].apply(eval, args=({}, {"var": var}))