This is because you cannot use and on numpy arrays. You need to replace the and with * and the or with + for numpy boolean arrays. (and do not forget to add parentheses).

Answer from Nicolas Barbey on Stack Overflow
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.piecewise.html
numpy.piecewise — NumPy v2.4 Manual
This is similar to choose or select, except that functions are evaluated on elements of x that satisfy the corresponding condition from condlist. ... |-- |funclist[0](x[condlist[0]]) out = |funclist[1](x[condlist[1]]) |... |funclist[n2](x[condlist[n2]]) |-- ... Try it in your browser! ... Define the signum function, which is -1 for x < 0 and +1 for x >= 0. >>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.])
🌐
w3resource
w3resource.com › numpy › functional-programming › piecewise.php
NumPy Functional programming: piecewise() function - w3resource
This is similar to choose or select, except that functions are evaluated on elements of x that satisfy the corresponding condition from condlist. ... |-- |funclist[0](x[condlist[0]]) out = |funclist[1](x[condlist[1]]) |... |funclist[n2](x[condlist[n2]]) |-- ... Define the sigma function, which is -1 for x < 0 and +1 for x >= 0. >>> import numpy as np >>> x = np.linspace(-3.5, 3.5, 5) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1])
🌐
Python Pool
pythonpool.com › home › blog › all about numpy piecewise function
All about Numpy Piecewise Function - Python Pool
June 8, 2021 - It can have only one conditional statement and only two possible values. Whereas for the piecewise() function, we can have multiple conditional statements and multiple possibilities for output.
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.piecewise.html
numpy.piecewise — NumPy v2.2 Manual
This is similar to choose or select, except that functions are evaluated on elements of x that satisfy the corresponding condition from condlist. ... |-- |funclist[0](x[condlist[0]]) out = |funclist[1](x[condlist[1]]) |... |funclist[n2](x[condlist[n2]]) |-- ... Define the signum function, which is -1 for x < 0 and +1 for x >= 0. >>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.])
🌐
Sketchy thoughts
sfalsharif.wordpress.com › 2009 › 12 › 18 › piecwise-function-definitions-in-numpy
Piecewise function definitions in NumPy | Sketchy thoughts
March 28, 2010 - The basic format of the piecewise statement, ignoring optional arguments, is numpy.piecewise(x, condlist, funclist) , where x is a NumPy ndarray, condlist is the list of boolean arrays upon which the piecwise function defenition depends, and funclist is a list of functions corresponding to each of the boolean conditons.
🌐
Medium
medium.com › @amit25173 › understanding-numpy-piecewise-with-examples-53b4fc9b8dcf
Understanding numpy.piecewise with Examples | by Amit Yadav | Medium
February 8, 2025 - 🔹 If x < 0 → Directly assign -1. 🔹 If 0 ≤ x < 3 → Apply x**2. 🔹 If x ≥ 3 → Multiply it by 2. ... Everything is done without writing loops or messy conditionals! Why numpy.piecewise is Better Than Using np.where()?
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.piecewise.html
numpy.piecewise — NumPy v2.1 Manual
This is similar to choose or select, except that functions are evaluated on elements of x that satisfy the corresponding condition from condlist. ... |-- |funclist[0](x[condlist[0]]) out = |funclist[1](x[condlist[1]]) |... |funclist[n2](x[condlist[n2]]) |-- ... Define the signum function, which is -1 for x < 0 and +1 for x >= 0. >>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.])
🌐
NumPy
numpy.org › doc › 1.23 › reference › generated › numpy.piecewise.html
numpy.piecewise — NumPy v1.23 Manual
This is similar to choose or select, except that functions are evaluated on elements of x that satisfy the corresponding condition from condlist. ... |-- |funclist[0](x[condlist[0]]) out = |funclist[1](x[condlist[1]]) |... |funclist[n2](x[condlist[n2]]) |-- ... Define the sigma function, which is -1 for x < 0 and +1 for x >= 0. >>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.])
Find elsewhere
🌐
GitHub
github.com › numpy › numpy › pull › 5187
Enhance piecewise to allow functions to have arbitrary number of input arguments by pbrod · Pull Request #5187 · numpy/numpy
Made piecewise function simpler and more general. The new piecewise function allows functions of the type f(x0, x1,.. ,xn) i.e. to have arbitrary number of input arguments that are evaluated condit...
Author   numpy
🌐
ProgramCreek
programcreek.com › python › example › 102171 › numpy.piecewise
Python Examples of numpy.piecewise
GCP: ratings from https://cloud.google.com/compute/docs/disks/performance#ssd-pd-performance AWS: to achieve good performance on EBS, one needs to use an EBS-optimized VM instance, and the smallest VM instance that can be EBS optimized is *.large VM types (e.g., c4.large), those comes with 2 cores. ratings from http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html """ if self._provider == GCP: value = self._iops self._cpu_count = int( numpy.piecewise([value], [[value <= 15000], [ (value > 15000) & (value <= 25000) ], [value > 25000]], [lambda x: 1, lambda x: 16, lambda x: 32])) elif self._provider == AWS: self._cpu_count = 2
🌐
NumPy
numpy.org › doc › 1.19 › reference › generated › numpy.piecewise.html
numpy.piecewise — NumPy v1.19 Manual
This is similar to choose or select, except that functions are evaluated on elements of x that satisfy the corresponding condition from condlist. ... |-- |funclist[0](x[condlist[0]]) out = |funclist[1](x[condlist[1]]) |... |funclist[n2](x[condlist[n2]]) |-- ... Define the sigma function, which is -1 for x < 0 and +1 for x >= 0. >>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.])
🌐
University of Texas at Austin
het.as.utexas.edu › HET › Software › Numpy › reference › generated › numpy.piecewise.html
numpy.piecewise — NumPy v1.9 Manual
This is similar to choose or select, except that functions are evaluated on elements of x that satisfy the corresponding condition from condlist. ... |-- |funclist[0](x[condlist[0]]) out = |funclist[1](x[condlist[1]]) |... |funclist[n2](x[condlist[n2]]) |-- ... Define the sigma function, which is -1 for x < 0 and +1 for x >= 0. >>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.])
🌐
NumPy
numpy.org › doc › 2.3 › reference › generated › numpy.piecewise.html
numpy.piecewise — NumPy v2.3 Manual
This is similar to choose or select, except that functions are evaluated on elements of x that satisfy the corresponding condition from condlist. ... |-- |funclist[0](x[condlist[0]]) out = |funclist[1](x[condlist[1]]) |... |funclist[n2](x[condlist[n2]]) |-- ... Try it in your browser! ... Define the signum function, which is -1 for x < 0 and +1 for x >= 0. >>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.])
Top answer
1 of 1
12

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 & (not 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])
🌐
Mabouali
mabouali.com › 2024 › 02 › 04 › piecewise-linear-functions-part-i
Piecewise-Linear Functions: Part I – Moe’s Homepage
If the first condition is true, the first function from the list is returned; If the second condition is true, the second function is returned. ... import numpy as np def my_piecewise_function_2(x): return np.piecewise( x, # The value at which the piecewise function should be evaluated [ # ...
🌐
JAX Documentation
docs.jax.dev › en › latest › _autosummary › jax.numpy.piecewise.html
jax.numpy.piecewise — JAX documentation
An array which is the result of evaluating the functions on x at the specified conditions. ... Here’s an example of a function which is zero for negative values, and linear for positive values: >>> x = jnp.array([-4, -3, -2, -1, 0, 1, 2, 3, 4]) >>> condlist = [x < 0, x >= 0] >>> funclist = [lambda x: 0 * x, lambda x: x] >>> jnp.piecewise(x, condlist, funclist) Array([0, 0, 0, 0, 0, 1, 2, 3, 4], dtype=int32)
🌐
SciPy
docs.scipy.org › doc › › numpy-1.8.1 › reference › generated › numpy.piecewise.html
numpy.piecewise — NumPy v1.8 Manual
This is similar to choose or select, except that functions are evaluated on elements of x that satisfy the corresponding condition from condlist. ... |-- |funclist[0](x[condlist[0]]) out = |funclist[1](x[condlist[1]]) |... |funclist[n2](x[condlist[n2]]) |-- ... Define the sigma function, which is -1 for x < 0 and +1 for x >= 0. >>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.])
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.piecewise.html
numpy.piecewise — NumPy v2.5.dev0 Manual
This is similar to choose or select, except that functions are evaluated on elements of x that satisfy the corresponding condition from condlist. ... |-- |funclist[0](x[condlist[0]]) out = |funclist[1](x[condlist[1]]) |... |funclist[n2](x[condlist[n2]]) |-- ... Try it in your browser! ... Define the signum function, which is -1 for x < 0 and +1 for x >= 0. >>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.])