Evaluate a piecewise-defined function.
Given a set of conditions and corresponding functions, evaluate each function on the input data wherever its condition is true.
Parameters : | x : ndarray
condlist : list of bool arrays
funclist : list of callables, f(x,*args,**kw), or scalars
args : tuple, optional
kw : dict, optional
|
---|---|
Returns : | out : ndarray
|
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
Define the sigma function, which is -1 for x < 0 and +1 for x >= 0.
>>> x = np.arange(6) - 2.5
>>> np.piecewise(x, [x < 0, x >= 0], [-1, 1])
array([-1., -1., -1., 1., 1., 1.])
Define the absolute value, which is -x for x <0 and x for x >= 0.
>>> np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x])
array([ 2.5, 1.5, 0.5, 0.5, 1.5, 2.5])