如何使用 eval 数据框方法中的自定义函数作为表达式中的一部分?

5

我正在使用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

有没有一种方法可以在表达式中使用自定义函数?
注意:我知道这可能会有风险,但这是我的责任。
1个回答

9

在调用本地变量或本地函数时,请使用@

In [45]: equation = 'D = sqrt(A) + B + @custom()'
#  NOTE:   ------------>               ^

In [46]: df.eval(equation, inplace=True)

In [47]: df
Out[47]:
    A     B   C            D
0   0     0  25     3.000000
1  10     0  25     6.162278
2   0  1000  25  1003.000000
3  10  1000  25  1006.162278
4  10     0  40     6.162278
5  30     0  40     8.477226

学到了新东西,先生。+1 - Bharath M Shetty
谢谢@maxu,你是怎么知道的?哈哈,我一直在测试它,我有另一个相关问题 - ChesuCR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接