Jerry Londergaard Jerry Londergaard - 1 year ago 146
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
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

  3. Try something else (maybe
    ) ?


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download