As title says, Is there a way to support round, ceiling, min, max, floor functions in pandas eval.
DataFrame:
JavaScript
x
5
1
import pandas as pd
2
import numexpr as ne
3
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]}
4
df = pd.DataFrame(data=op_d)
5
abs() and sqrt() function works with pandas eval. i.e.
JavaScript
1
3
1
df.eval('TT = abs(sqrt(Q1+Q2)-Q2)',inplace=True)
2
df
3
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:
- Arithmetic operations inside these functions are necessary (i.e. sum, multiplication, div of two columns).
- 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.
JavaScript
1
6
1
from py_expression_eval import Parser
2
parser = Parser()
3
4
dct = {'Q1':df['Q1'],'Q2':df['Q2'],'max':max1,'round':getround}
5
df['check']=parser.parse('round(Q1/Q2)').evaluate(dct)
6
library source: https://github.com/Axiacore/py-expression-eval
Hope this helps others.