Ability to read and eval() any arbitrary function / lambda from JSON config file
<p>I am looking for a way to a user to enter any arbitrary python formula, store the formula in a text file or a JSON file, then have Python read the formula and apply the transformation to a data frame.  My original requirement is to have a frontend web UI where the user can specify any transformation rules / scripts / formulas.</p>

<p>For example:</p>

<pre><code>import pandas as pd
import numpy as np

df = pd.DataFrame({'state_full': ['Alabama', 'Alaska', 'American Samoa'],
'state_abbrev': ['Ala.', 'Alaska', np.nan],
'state_postal': ['AL', 'AK', 'AS']}, index=[0, 1, 2])

df['state_abbrev'].str.upper()   # This works, but I need to read the formula from a file
</code></pre>

<p>Want ability to read any arbitrary lambda function from a config file in JSON:</p>

<pre><code>lambda_transform_str = "str.upper()"   
df['state_abbrev'].eval(lambda_transform_str)
</code></pre>

<p>Encountered Error:
AttributeError: 'Series' object has no attribute 'eval'</p>

<p>The <code>eval</code> function in Python isn't a method attached to strings; it's a globally available function. You should be able to call it like:</p>

<pre><code>eval(..)
</code></pre>

<p>If you're trying to transform <code>df['state_abbrev']</code> according to the contents of <code>lambda_transform_str</code>, you need to approach this problem another way.</p>

<pre><code>eval('"{}".upper()'.format(df['state_abbrev']))
</code></pre>

<p>This has limitations obviously since you have to ensure that your textual functions are all compatible with the <code>str</code> type, but that's an implementation detail I'll leave up to you.</p>

<p>As @martineau pointed out in the comments, be wary of using <code>eval</code>. It can expose codebases to serious security vulnerabilities.</p>

python json lambda