Search code examples
pythonfunctionmethodseval

How can use string as a function method in python?


Hi I am using python and have a dataframe (df) as below:

        c      param_values
0   abs_energy  NaN
1   absolute_sum_of_changes NaN
2   agg_autocorrelation [{'f_agg': 'median', 'maxlag': 40}, {'f_agg': ...
3   agg_linear_trend    [{'f_agg': 'max', 'chunk_len': 5, 'attr': 'int...
4   approximate_entropy [{'m': 2, 'r': 0.3}, {'m': 2, 'r': 0.1}, {'m':...

I am iterating the above dataframe as below:

I have an import from tsfresh.feature_extraction import feature_calculators as fc

for i,v in df[1:].iterrows():
    dispatcher={v["calculators"]:eval(str(fc.v["calculators"]))}
    t = eval(v["calculators"],dispatcher)
    print(t)

But I get the following error

AttributeError: module 'tsfresh.feature_extraction.feature_calculators' has no attribute 'v'

I want to evaluate fc.abs_energy,fc.absolute_sum_of_changes,fc.agg_autocorrelation('median','40') etc. How can I find this by iterating the above dataframe. I have tried using eval as shown above but in vain. Please suggest some method. If I have under emphasised/ over emphasised something please let me know in the comments. Thank you


Solution

  • I think you have to try importing like this:

    from tsfresh.feature_extraction.feature_calculators import abs_energy,absolute_sum_of_changes,agg_autocorrelation

    And then use this in eval like this:

    eval(str(v["calculators"]))

    Solution 2

    Alternatively, you can change your data in your DataFrame to be like fc.abs_energy instead of abs_energy and import your module without change:

    from tsfresh.feature_extraction import feature_calculators as fc

    Caution

    Do not forget to concatenate () to your string to call the desired function. For example you have to call abs_energy function like this:

    eval('abs_energy()')