Jerry Londergaard Jerry Londergaard - 1 month ago 6
Python Question

Evaluating stringified formulas with pandas datatypes

Using python2 I want to be able to parse and evaluate formulas that have been saved as a string. Basically, I want clients to be able to describe formulas to apply over their data. Some of these formulas may have custom functions. Here's two examples:

x / y
SumF(x) / y # Here SumF is my own custom function


I started using Sympy, but I hit a snag in that I can't get it doesn't work when evaluating pandas DataFrames (i.e it seems to convert the Dataframe to a list consisting of the column labels...). I suspect that Sympy just doesn't support pandas DataFrame/Series objects. I really want to use these objects as it will make life so much easier for all the usual reasons.

Plain old
eval()
will also work, but I was hoping to avoid it just for the usual pitfalls.

What would people suggest from the following:


  1. Get Sympy to somehow work

  2. Use
    eval()

  3. Try something else (maybe
    ast.literal_eval()
    ) ?



Cheers

Answer

You can use pd.eval which will try and use an optimised parser if it can, and also disallows eval('input()').

Comments