Skip to content
Advertisement

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':['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() and sqrt() function works with pandas eval. i.e.

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

can anyone suggest how to access rest of the functions in eval? I also tried ‘local_dict’ in eval to see if I can define custom functions and call them but it didn’t work.

Note:

  1. Arithmetic operations inside these functions are necessary (i.e. sum, multiplication, div of two columns).
  2. I am aware of issues around usage of ‘eval’ functions and taking necessary measurements.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement