如果表达式包含sympy对象

如果表达式包含sympy对象

本文介绍了如果表达式包含sympy对象,则Lambdify'ed表达式在与数组一起使用时会引发TypeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用sympy来创建一个表达式,然后用



然后,尝试使用

 导入pandas 
df = pandas.DataFrame([1,2,3],columns = ['a'])

f(df ['a'])

我得到:

  TypeError Traceback(最近一次调用最后一次) )
/home/gold/venvs/venv_python3.5/lib/python3.5/site-packages/sympy/core/cache.py in wrapper(* args,** kwargs)
92试试:
---> 93 retval = cfunc(* args,** kwargs)
94除TypeError:

/home/gold/venvs/venv_python3.5/lib/python3.5/site-packages/pandas __hash中的/core/generic.py __(self)
830引发TypeError('{0!r}对象是可变的,因此它们不能是'
- > 831'hashed'.format(self .__ class __.__ name__))
832

TypeError:'Series'对象是可变的,因此它们不能被散列

在处理上述异常时,另一个异常发生:

SympifyError Traceback(最近一次调用最后一次)
< ipython-input-25-d0ba59fbbc02> in< module>()
2 df = pandas.DataFrame([1,2,3],columns = ['a'])
3
----> 4 f(df ['a'])

/home/gold/venvs/venv_python3.5/lib/python3.5/site-packages/sympy/__init__.py in< lambda>( _Dummy_21)

/home/gold/venvs/venv_python3.5/lib/python3.5/site-packages/sympy/functions/elementary/miscellaneous.py in sqrt(arg)
113
114#arg = sympify(arg)由Pow
处理 - > 115返回Pow(arg,S.Half)
116
117

/home/gold/venvs/venv_python3.5/lib/python3.5/site-packages/sympy/core/cache.py in wrapper(* args,** kwargs)
93 retval = cfunc(* args,** kwargs)
94除TypeError:
---> 95 retval = func(* args,** kwargs)
96 return retval
97

/home/gold/venvs/venv_python3.5/lib/python3.5/site-packages/sympy/core/power.py in __new __(cls,b,e,evaluate)
168来自sympy.functions.elementary.exponential import exp_polar
169
- > 17 0 b = _sympify(b)
171 e = _sympify(e)
172如果评估:

/home/gold/venvs/venv_python3.5/lib/python3.5 _site-packages/sympy/core/sympify.py in _sympify(a)
353
354
- > 355 return sympify(a,strict = True)
356
357

/home/gold/venvs/venv_python3.5/lib/python3.5/site-packages/sympy /core/sympify.py in sympify(a,locals,convert_xor,strict,rational,evaluate)
275
276 if strict:
- > 277引发SympifyError(a)
278
279如果可迭代(a):

SympifyError:SympifyError:0 1
1 2
2 3
名称:a,dtype:int64


解决方案

numpy,这是有效的:

 在[845]中:df = pd.DataFrame([1,2,3],columns = ['a'])
In [846]:arr = np.array([1,2,3])
In [847] ]:f = sympy.lambdify(x,sympy.sqrt(x),numpy)

[849]:f(arr)
Out [849]:array([ 1.,1.41421356,1.73205081])$ ​​b $ b在[850]中:f(df)
输出[850]:
a
0 1.000000
1 1.414214
2 1.732051

但是替代品没有:

 在[851]中:f(x)
...
AttributeError:'Symbol'对象没有属性'sqrt'

我还没有研究过 lambdify docs,知道我是否可以使两者都在一个功能中工作。

  f = sympy.lambdify(x,sympy.sqrt(x),modules =(sympy,numpy))

处理 sympy 但不处理 numpy 参数。



看起来没有指定模块应该与 modules = [math,mpmath,sympy,numpy]



表达式运算符很好,甚至组合符号和数组:

 在[926]中:f = sympy.lambdify((x,y) ,x + y,(numpy,sympy))
In [927]:f(x,y)
Out [927]:x + y
[928] :f(arr,arr)
Out [928]:array([2,4,6])
In [929]:f(arr,x)
Out [929]:数组([x + 1,x + 2,x + 3],dtype = object)

I可能还没有发现任何你尚未发现的东西。


I'm using sympy to create an expression that is then displayed as latex with sympy.init_printing(). The expression is used in calculations after being lambdified to a function named f.

However, when using an array or a Series object as an argument to f I get a TypeError, if the lambdified expression contains a sympy object (e.g. sympy.sqrt()). If I had used **.5 instead of the sqrt I would get no error (but it wouldn't display the root in IPython).

Question:
How can I use arrays or Series on a function I created through sympy.lambdify()?


The following code is a (simplified) demo of the problem:

import sympy
import numpy
sympy.init_printing()

x = sympy.symbols('x')

_f = lambda x: sympy.sqrt(x)
f = sympy.lambdify(x, _f(x), (sympy, numpy))

f(x)

This results in a pretty root:

Then, trying to use

import pandas
df = pandas.DataFrame([1,2,3], columns=['a'])

f(df['a'])

I get:

TypeError                                 Traceback (most recent call last)
/home/gold/venvs/venv_python3.5/lib/python3.5/site-packages/sympy/core/cache.py in wrapper(*args, **kwargs)
     92                 try:
---> 93                     retval = cfunc(*args, **kwargs)
     94                 except TypeError:

/home/gold/venvs/venv_python3.5/lib/python3.5/site-packages/pandas/core/generic.py in __hash__(self)
    830         raise TypeError('{0!r} objects are mutable, thus they cannot be'
--> 831                         ' hashed'.format(self.__class__.__name__))
    832

TypeError: 'Series' objects are mutable, thus they cannot be hashed

During handling of the above exception, another exception occurred:

SympifyError                              Traceback (most recent call last)
<ipython-input-25-d0ba59fbbc02> in <module>()
      2 df = pandas.DataFrame([1,2,3], columns=['a'])
      3
----> 4 f(df['a'])

/home/gold/venvs/venv_python3.5/lib/python3.5/site-packages/sympy/__init__.py in <lambda>(_Dummy_21)

/home/gold/venvs/venv_python3.5/lib/python3.5/site-packages/sympy/functions/elementary/miscellaneous.py in sqrt(arg)
    113     """
    114     # arg = sympify(arg) is handled by Pow
--> 115     return Pow(arg, S.Half)
    116
    117

/home/gold/venvs/venv_python3.5/lib/python3.5/site-packages/sympy/core/cache.py in wrapper(*args, **kwargs)
     93                     retval = cfunc(*args, **kwargs)
     94                 except TypeError:
---> 95                     retval = func(*args, **kwargs)
     96                 return retval
     97

/home/gold/venvs/venv_python3.5/lib/python3.5/site-packages/sympy/core/power.py in __new__(cls, b, e, evaluate)
    168         from sympy.functions.elementary.exponential import exp_polar
    169
--> 170         b = _sympify(b)
    171         e = _sympify(e)
    172         if evaluate:

/home/gold/venvs/venv_python3.5/lib/python3.5/site-packages/sympy/core/sympify.py in _sympify(a)
    353
    354     """
--> 355     return sympify(a, strict=True)
    356
    357

/home/gold/venvs/venv_python3.5/lib/python3.5/site-packages/sympy/core/sympify.py in sympify(a, locals, convert_xor, strict, rational, evaluate)
    275
    276     if strict:
--> 277         raise SympifyError(a)
    278
    279     if iterable(a):

SympifyError: SympifyError: 0    1
1    2
2    3
Name: a, dtype: int64
解决方案

With "numpy", this works:

In [845]: df=pd.DataFrame([1,2,3], columns=['a'])
In [846]: arr=np.array([1,2,3])
In [847]: f = sympy.lambdify(x, sympy.sqrt(x),"numpy")

In [849]: f(arr)
Out[849]: array([ 1.        ,  1.41421356,  1.73205081])
In [850]: f(df)
Out[850]:
          a
0  1.000000
1  1.414214
2  1.732051

but the sympy substitute does not:

In [851]: f(x)
...
AttributeError: 'Symbol' object has no attribute 'sqrt'

I haven't studied the lambdify docs enough to know if I can make both work in one function or not.

f = sympy.lambdify(x, sympy.sqrt(x),modules=("sympy", "numpy"))

handles the sympy but not the numpy arguments.

It looks like not specifying modules should be the same as modules = ["math", "mpmath", "sympy", "numpy"].

An expression with operators works nicely, even combining symbols and arrays:

In [926]: f = sympy.lambdify((x,y), x+y, ("numpy","sympy"))
In [927]: f(x,y)
Out[927]: x + y
In [928]: f(arr,arr)
Out[928]: array([2, 4, 6])
In [929]: f(arr,x)
Out[929]: array([x + 1, x + 2, x + 3], dtype=object)

I probably haven't discovered anything that you haven't already.

这篇关于如果表达式包含sympy对象,则Lambdify'ed表达式在与数组一起使用时会引发TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:07