我正在使用 sympy 创建一个表达式,然后将其显示为乳胶sympy.init_printing() http://docs.sympy.org/dev/tutorial/printing.html#setting-up-pretty-printing。该表达式在被羔羊化为名为的函数后用于计算f
.
但是,当使用数组或Series
对象作为参数f
如果 lambda 化表达式包含 sympy 对象(例如sympy.sqrt()
)。如果我用过**.5
而不是sqrt
我不会收到任何错误(但它不会在 IPython 中显示根)。
问题:
我如何使用数组或Series
在我通过创建的函数上sympy.lambdify() http://docs.sympy.org/dev/modules/utilities/lambdify.html?
以下代码是该问题的(简化的)演示:
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)
这会产生一个漂亮的根:
然后,尝试使用
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