bundles / numpy 2.4.4 / numpy / piecewise
_ArrayFunctionDispatcher
numpy:piecewise
Signature
def piecewise ( x , condlist , funclist , * args , ** kw ) Summary
Evaluate a piecewise-defined function.
Extended Summary
Given a set of conditions and corresponding functions, evaluate each function on the input data wherever its condition is true.
Parameters
x: ndarray or scalarThe input domain.
condlist: list of bool arrays or bool scalarsEach boolean array corresponds to a function in
funclist. Wherevercondlist[i]is True,funclist[i](x)is used as the output value.Each boolean array in
condlistselects a piece ofx, and should therefore be of the same shape asx.The length of
condlistmust correspond to that offunclist. If one extra function is given, i.e. iflen(funclist) == len(condlist) + 1, then that extra function is the default value, used wherever all conditions are false.funclist: list of callables, f(x,*args,**kw), or scalarsEach function is evaluated over
xwherever its corresponding condition is True. It should take a 1d array as input and give a 1d array or a scalar value as output. If, instead of a callable, a scalar is provided then a constant function (lambda x: scalar) is assumed.args: tuple, optionalAny further arguments given to piecewise are passed to the functions upon execution, i.e., if called
piecewise(..., ..., 1, 'a'), then each function is called asf(x, 1, 'a').kw: dict, optionalKeyword arguments used in calling piecewise are passed to the functions upon execution, i.e., if called
piecewise(..., ..., alpha=1), then each function is called asf(x, alpha=1).
Returns
out: ndarrayThe output is the same shape and type as x and is found by calling the functions in
funcliston the appropriate portions ofx, as defined by the boolean arrays incondlist. Portions not covered by any condition have a default value of 0.
Notes
This is similar to choose or select, except that functions are evaluated on elements of x that satisfy the corresponding condition from condlist.
The result is
|-- |funclist[0](x[condlist[0]]) out = |funclist[1](x[condlist[1]]) |... |funclist[n2](x[condlist[n2]]) |--
Examples
import numpy as np
✓x = np.linspace(-2.5, 2.5, 6) np.piecewise(x, [x < 0, x >= 0], [-1, 1])✓
np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x])
✗y = -2 np.piecewise(y, [y < 0, y >= 0], [lambda x: -x, lambda x: x])✓
See also
- choose
- select
- where
Aliases
-
numpy.piecewise