Skip to content Skip to sidebar Skip to footer

Calling Round(), Ceiling(), Floor(), Min(), Max() In Pandas Eval

As title says, Is there a way to support round, ceiling, min, max, floor functions in pandas eval. DataFrame: import pandas as pd import numexpr as ne op_d = {'ID': [1, 2,3],'V':[

Solution 1:

You can't

DataFrame.eval only supports 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.

If it's not on that list you can't call it beacause "Function calls other than math functions [are not allowed syntax]"


That being said, it might be possible to implement some of those functions in terms of more basic operations. Here I've implemented an eval equivalent of np.sign. But IMO that obfuscates the operation far too much and isn't very useful, so really you need to move away from eval

Solution 2:

With the help of 'py_expression_eval' libary, I was able to work out arithmatic operations inside user defined functions.

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)

library source: https://github.com/Axiacore/py-expression-eval

Hope this helps others.

Post a Comment for "Calling Round(), Ceiling(), Floor(), Min(), Max() In Pandas Eval"