NumPy piecewise: Conditional Array Values

Quick Answer

Call np.piecewise(x, condlist, funclist) to apply different constants or functions to elements selected by boolean conditions. Each condition should match x in shape. If funclist has one extra item, that item supplies the default for elements not covered by any condition.

NumPy piecewise condition arrays functions and default output
numpy.piecewise applies each function where its condition is true and can use an extra function as the uncovered-value default.

np.piecewise() applies different values or functions to different parts of an array. It is useful when each condition has its own rule.

The official NumPy piecewise documentation explains condlist and funclist. The NumPy where documentation is useful for simpler two-way choices.

Use piecewise() when conditions are easier to read as separate rules. For one simple true/false choice, np.where() is often shorter.

The function is best for formulas that are naturally described as ranges. Each condition names a slice of the input, and each matching slice receives its own output rule.

Apply Constants By Condition

The condition list selects positions in the input array, and the function list supplies the output for those positions. piecewise selects formulas from conditions, while NumPy choose() Function Examples Guide selects values from indexed choice arrays.

import numpy as np

x = np.array([-2, -1, 0, 1, 2])

result = np.piecewise(
    x,
    [x < 0, x == 0, x > 0],
    [-1, 0, 1],
)

print(result)

This maps negative values to -1, zero to 0, and positive values to 1. Each condition produces one part of the final output. For a standard step discontinuity without writing condition branches manually, NumPy heaviside Guide for Step Functions provides NumPy’s Heaviside definition and the value at zero.

The output shape matches the input shape, which makes it easy to compare the result against the original array.

Keep the condition order readable. When possible, write conditions from low to high, left to right, or from most specific to most general so the rule list has an obvious flow.

Python Pool infographic showing an input array, Boolean conditions, branches, and NumPy piecewise
Conditions: An input array, Boolean conditions, branches, and NumPy piecewise.

Use Functions In funclist

Items in funclist can be callables. NumPy passes the matching values to the function.

import numpy as np

x = np.array([-3, -2, -1, 0, 1, 2, 3])

result = np.piecewise(
    x,
    [x < 0, x >= 0],
    [lambda values: values * values, lambda values: values + 10],
)

print(result)

The first function squares negative values. The second function adds 10 to zero and positive values.

Functions should be written to handle arrays, not just one scalar value, because each branch receives all matching values at once.

This vectorized call style is important for performance. The function runs once per branch with a slice of data, rather than once for every individual item.

Use A Default Value

If funclist has one more item than condlist, the final item is used as the default for values that match none of the conditions.

import numpy as np

x = np.array([5, 15, 25, 35])

result = np.piecewise(
    x,
    [x < 10, x > 30],
    ["low", "high", "middle"],
)

print(result)

Values below 10 become low, values above 30 become high, and the rest use the default middle.

Without a default, unmatched positions receive zero-like values based on the output dtype. An explicit default is usually clearer.

Defaults also make intent visible in reviews. A reader can immediately see what happens outside the named ranges instead of guessing whether zero was intentional.

Python Pool infographic mapping each condition to a scalar or function and selecting output values
Branch values: Each condition to a scalar or function and selecting output values.

Build A Piecewise Formula

Piecewise math is a natural fit when different numeric ranges need different formulas.

import numpy as np

x = np.linspace(-2, 2, 5)

y = np.piecewise(
    x,
    [x < 0, x >= 0],
    [lambda values: -values, lambda values: values ** 2],
)

print(x)
print(y)

This uses absolute-value-like behavior on the negative side and a square on the nonnegative side.

For plotting or simulation, keeping the rules inside one piecewise() call can make the formula easier to inspect.

When the formulas are longer, define named helper functions before calling piecewise(). That keeps the rule list compact while still preserving vectorized behavior.

Combine Several Ranges

Multiple conditions can describe bands or categories.

import numpy as np

scores = np.array([45, 62, 74, 88, 96])

grades = np.piecewise(
    scores,
    [scores < 60, (scores >= 60) & (scores < 75), scores >= 75],
    ["fail", "pass", "strong"],
)

print(grades)

The middle condition uses & because it combines two NumPy Boolean masks. Parentheses are required around each comparison.

When ranges are adjacent, check the boundary values carefully so every value lands in the intended category.

It is also worth checking dtype. If every output is a string label, the result becomes a string array. If outputs are numeric, NumPy chooses a numeric dtype that can hold the branch results.

Python Pool infographic comparing matched conditions, default value, overlap, order, and broadcast shape
Default branch: Matched conditions, default value, overlap, order, and broadcast shape.

Compare piecewise With where

np.where() is often better for one condition and two possible outputs.

import numpy as np

x = np.array([-2, -1, 0, 1, 2])

with_where = np.where(x < 0, -x, x)
with_piecewise = np.piecewise(x, [x < 0, x >= 0], [lambda v: -v, lambda v: v])

print(with_where)
print(with_piecewise)

Both results are the same in this simple case. where() is shorter, while piecewise() scales better when there are several named conditions.

Choose the function that keeps the rule easiest to read, not the one with the fewest characters.

As a rough rule, use where() for binary choices and piecewise() when the reader benefits from seeing a list of named conditions.

Common Mistakes

Do not mismatch condition and function counts unless the extra function is intended as the default.

Do not forget that overlapping conditions are applied in list order. Later rules can write to positions already handled by earlier rules, so make ranges exclusive when possible.

Do not use scalar-only functions in funclist. Branch functions receive arrays of matching values.

The practical default is to use np.where() for one simple condition and np.piecewise() when several conditions each need their own value or formula.

Python Pool infographic testing no match, overlapping masks, dtype, broadcasting, and empty arrays
Piecewise checks: No match, overlapping masks, dtype, broadcasting, and empty arrays.

Apply Functions and Constants by Condition

Each condition in condlist selects the positions where the corresponding item in funclist is used. A scalar funclist item is treated as a constant; a callable receives the selected input.

import numpy as np

x = np.array([-2, -1, 0, 2, 5])
conditions = [x < 0, x == 0, x > 0]
functions = [-1, 0, lambda values: values * 2]

result = np.piecewise(x, conditions, functions)
print(result)

Make conditions mutually understandable and cover the intended domain. Overlapping conditions can make the result depend on the order in which conditions are applied, so document that choice.

Use an Explicit Default for Uncovered Values

If no condition is true, the default output is zero unless an extra function or scalar is provided. Give an explicit default when zero would be misleading.

import numpy as np

x = np.array([-2, 0, 3])
result = np.piecewise(
    x,
    [x > 0],
    [lambda values: values ** 2, -999],
)
print(result)  # [-999, -999, 9]

For simple element-wise conditions, compare np.where() or np.select() as well. Choose the function whose control flow is easiest to verify and whose conditions have compatible shapes.

Frequently Asked Questions

What does np.piecewise do?

It evaluates different constants or functions over the elements of an array selected by boolean condition arrays.

What shape should NumPy piecewise conditions have?

Each condition should have the same shape as x so every selected element maps to the intended output position.

How do I set a default value with np.piecewise?

Provide one more item in funclist than in condlist. The extra item is used where all conditions are false.

When should I use np.where or np.select instead?

Use them when nested choices or simple conditions are clearer there; piecewise is useful when each region maps to a callable or a scalar rule.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted