Ich benutze Python 3.X.Wie kann ich eine benutzerdefinierte Funktion innerhalb eines Ausdrucks mit der Eval Dataframe-Methode verwenden?
Mit der eingebauten Funktion eval()
Sie eine dictionaty von Objekten verwenden können, um eine benutzerdefinierte Funktion wie folgt zu verwenden:
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)
Aber die eval()
Datenrahmen Methode funktioniert nicht so. Sie können nur diese integrierten Funktionen nutzen:
Die unterstützten mathematischen Funktionen sin sind, cos, exp, log, expm1, log1p, sqrt, sinh, cosh, tanh, arcsin, arccos, arctan, arccosh, arcsinh , arctanh, abs und 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
gibt es eine Möglichkeit, eine benutzerdefinierte Funktion in dem Ausdruck zu benutzen?
HINWEIS: Ich weiß, es könnte bedangerous, aber es ist mir
etwas Neues gelernt Sir. +1 – Dark
@Bharath, danke! :) – MaxU
Danke @maxu, woher weißt du das? haha Ich habe es getestet und ich habe [eine andere Frage dazu] (https://stackoverflow.com/questions/47163401/how-to-return-a-numpy-array-or-list-in-a-custom -function-using-the-eval-datafram) – ChesuCR