我正在使用Python 3.X。
使用内置函数eval()
,您可以使用对象字典来使用自定义函数,如下所示:
from math import *
def one():
# some operations
return 1
functions = {
'__builtins__': None,
'sqrt': sqrt,
'one': one,
}
variables = {
'__builtins__': None,
'pi': pi,
}
expression = 'sqrt(34 * pi) + one()'
eval(expression, variables, functions)
然而,eval()
数据框方法并不像那样工作。您只能使用这些内置函数:
支持的数学函数有 sin、cos、exp、log、expm1、log1p、sqrt、sinh、cosh、tanh、arcsin、arccos、arctan、arccosh、arcsinh、arctanh、abs 和 arctan2
import pandas as pd
import numpy as np
from math import *
df = pd.DataFrame({
'A': [0, 10, 0, 10, 10, 30],
'B': [0, 0, 1000, 1000, 0, 0],
'C': [25, 25, 25, 25, 40, 40]
})
def custom():
# some operations
return 3
functions = {
'custom': custom
}
variables = {
'pi': pi
}
equation = 'D = sqrt(A) + B + custom()'
df.eval(
equation, global_dict=variables, local_dict=functions,
engine='numexpr', inplace=True
)
# ERROR: "custom" is not a supported function
有没有一种方法可以在表达式中使用自定义函数?
注意:我知道这可能会有风险,但这是我的责任。