在 pandas eval 中调用 round()、ceiling()、floor()、min()、max()

Calling round(), ceiling(), floor(), min(), max() in pandas eval

正如标题所说,有没有办法在 pandas eval 中支持 round、ceiling、min、max、floor 函数。

数据框:

import pandas as pd
import numexpr as ne
op_d = {'ID': [1, 2,3],'V':['F','G','H'],'AAA':[0,1,1],'E':[102014,112019,122017] ,'D':['2019/02/04','2019/02/01','2019/01/01'],'DD':['2019-12-01','2016-05-31','2015-02-15'],'CurrentRate':[7.5,2,2],'NoteRate':[2,3,3],'BBB':[0,00,4],'Q1':[2,8,00],'Q2':[3,5,7],'Q3':[5,6,8]}
df = pd.DataFrame(data=op_d)

abs() 和 sqrt() 函数与 pandas eval 一起使用。即

df.eval('TT = abs(sqrt(Q1+Q2)-Q2)',inplace=True)
df

谁能建议如何访问 eval 中的其余函数?我还在 eval 中尝试了 'local_dict' 以查看我是否可以定义自定义函数并调用它们,但它没有用。

注:

  1. 这些函数内部的算术运算是必需的(即两列的求和、乘法、div)。
  2. 我知道 'eval' 功能的使用和采取必要的措施方面的问题。

你不能

DataFrame.evalsupports a limited set of math operations

Arithmetic operations except for the left shift (<<) and right shift (>>) operators, e.g., df + 2 * pi / s ** 4 % 42 - the_golden_ratio

Math functions: sin, cos, exp, log, expm1, log1p, sqrt, sinh, cosh, tanh, arcsin, arccos, arctan, arccosh, arcsinh, arctanh, abs, arctan2 and log10.

如果它不在该列表中,则不能调用它,因为“数学函数以外的函数调用[不允许使用语法]”


也就是说,可能可以根据更基本的操作来实现其中一些功能。 Here I've implemented an eval equivalent of np.sign。但是 IMO 混淆了太多的操作并且不是很有用,所以你真的需要远离 eval

在 'py_expression_eval' 库的帮助下,我能够在用户定义的函数中进行算术运算。

from py_expression_eval import Parser
parser = Parser()

dct = {'Q1':df['Q1'],'Q2':df['Q2'],'max':max1,'round':getround}
df['check']=parser.parse('round(Q1/Q2)').evaluate(dct)

图书馆来源:https://github.com/Axiacore/py-expression-eval

希望这对其他人有帮助。