In general, numpy arrays are very good at doing reasonable things when you just write code, as if they were just numbers. Chain comparisons are one of the rare exceptions. The error you see is essentially this (obfuscating bits using piecewise internal elements and formatting ipython errors):
>>> 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) >>>
Alternatively, you can use np.logical_and , but bitwise and works just fine.
As for plotting, numpy itself does not. Here is 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()
Note that piecewise is a moody beast. In particular, he needs the argument x as an array, and he will not even try to convert it if it is not (in numpy parlance: x should be ndarray , not 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])