Multiple Pieces in a numpy.piecewise

隐身守侯 提交于 2019-12-01 16:06:27

In general, numpy arrays are very good at doing sensible things when you just write the code as if they were just numbers. Chaining comparisons is one of the rare exceptions. The error you're seeing is essentially this (obfuscated a bit by piecewise internals and ipython error formatting):

>>> a = np.array([1, 2, 3])
>>> 1.5 < a
array([False,  True,  True], dtype=bool)
>>> 
>>> 1.5 < a < 2.5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> 
>>> (1.5 < a) & (a < 2.5)
array([False,  True, False], dtype=bool)
>>> 

You can alternatively use np.logical_and, but bitwise and works just fine here.

As far as plotting is concerned, numpy itself doesn't do any. Here's an example with matplotlib:

>>> import numpy as np
>>> def piecew(x):
...   conds = [x < 0, (x > 0) & (x < 1), (x > 1) & (x < 2), x > 2]
...   funcs = [lambda x: x+1, lambda x: 1, 
...            lambda x: -x + 2., lambda x: (x-2)**2]
...   return np.piecewise(x, conds, funcs)
>>>
>>> import matplotlib.pyplot as plt
>>> xx = np.linspace(-0.5, 3.1, 100)
>>> plt.plot(xx, piecew(xx))
>>> plt.show() # or plt.savefig('foo.eps')

Notice that piecewise is a capricious beast. In particular, it needs its x argument to be an array, and won't even try converting it if it isn't (in numpy parlance: x needs to be an ndarray, not an array_like):

>>> piecew(2.1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in piecew
  File "/home/br/.local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 690, in piecewise
    "function list and condition list must be the same")
ValueError: function list and condition list must be the same
>>> 
>>> piecew(np.asarray([2.1]))
array([ 0.01])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!