Python eval function with numpy arrays via string input with dictionaries

前端 未结 2 1408
-上瘾入骨i
-上瘾入骨i 2021-01-21 04:20

I am implementing the code in python which has the variables stored in numpy vectors. I need to perform simple operation: something like (vec1+vec2^2)/vec3. Each element of each

相关标签:
2条回答
  • 2021-01-21 05:02

    Pass the dictionary to python eval function:

    >>> var = {'a':np.array([1,2,2]),'b':np.array([2,1,3]),'c':np.array([3])}
    >>> formula = '2*a*(b/c)**2'
    >>> eval(formula, var)
    array([ 0.8889,  0.4444,  4.    ])
    
    0 讨论(0)
  • 2021-01-21 05:05

    Using numexpr, then you could do this:

    In [143]: import numexpr as ne
    In [146]: ne.evaluate('2*a*(b/c)**2', local_dict=var)
    Out[146]: array([ 0.88888889,  0.44444444,  4.        ])
    
    0 讨论(0)
提交回复
热议问题