All about Numpy Piecewise Function

Numpy is a library in python that is used for working with multi-dimensional arrays and matrices. With numpy, we can perform several logical and mathematical operations while using arrays in python. The library comes in handy because it processes the arrays and matrices in python at a faster rate. This article will be learning about one such function from the numpy library – the numpy piecewise function.

What is a piecewise function?

Piecewise functions are those functions in mathematics which behave differently with different input values. It is a function which has different sub functions.

For each interval, a sub-function is defined. Depending on the interval in which the input value lies, a sub-function is defined for it. Let us understand with the help of an example.

numpy piecewise

Here, we have defined a piecewise function ‘f(x)’ in the above image. It has been defined over three intervals –

  1. x < 0
  2. x >= 0 and x<10
  3. x>=10

If x is negative, then the sub-function x^2 would be applied to it. So, for example, if the value of x lies between 0 and 10 where 10 is exclusive, then the sub-function ( 10 – x ) would be applied to it.

And if the value of x would be greater than or equal to 10, then the sub-function ( 2x + 3 ) would be applied to it.

For Example :

If the input value is -10, then the function value would be (10)^2, which is 100.

If input value is 5, then the function value would be ( 10 – 5 ), which is 5.

For input value 11, the function value would be ( 2*(11) + 3 ), which is 25.

Why use numpy piecewise?

If we were to define the piecewise function for the above example using a user defined function, then the python code used would be:

def my_func(x):
  if x < 0:
    return x**2
  elif x >= 0 and x < 10:
    return 10 - x
  elif x > 10:
    return 2*x + 3

n = int(input('Enter Number:'))
print(my_func(n))  

Output:

Enter Number:11
25

Instead of defining a complete function, we can reduce the entire function code to a single line using NumPy’s piecewise function.

Syntax of Numpy Piecewise

The syntax of the piecewise function in the numpy library is:

numpy.piecewise(x, condlist, funclist, *args, **kw)

Parameters :

x: It is the input n dimensional array.

condlist: It is a list of boolean arrays. The ‘condlist’ size should be the same as the size of the parameter ‘funclist’. The function will consider only those values from ‘funclist’ for which the corresponding value in ‘condlist’ is True. If the length of ‘funclist’ is one more than the length of ‘condlist’, then that will be the default value when the condition is False.

funclist: It is a list of callables. It takes a one-dimensional array as an input and outputs a one-dimensional array or a scalar value.

args: The args parameter is an optional tuple that is passed to the function upon execution.

kw: A kw parameter is an optional dictionary that is passed to the function upon execution.

Return Value:

out: The output is an n-dimensional array that has the same size as the parameter ‘x.’ Depending on the boolean value of the condlist, it calls the function in funclist.

Numpy Piecewise in Python

Let us understand the practical implementation of NumPy’s piecewise function in python. First, we shall import the numpy library.

import numpy as np

Now, we shall use the linspace() function present in numpy to return evenly spaced numbers between a given interval. Here, we shall return 5 numbers between the intervals [ -10, 11 ].

x = np.linspace(-10, 11, 5)

We will now pass the x value as the first argument to the piecewise() function. Again, we will have the same conditions as the example discussed above.

Instead of the sub-functions, we will be passing values – 0, 1, and 10 for each condition, respectively. We will pass the three conditions as the second argument and the output value list as the third argument.

np.piecewise(x, [x < 0, ((x >= 0) & (x < 10)), x >= 10], [0, 1, 10])

The output value is:

array([ 0.,  0.,  1.,  1., 10.])

The Entire Code is:

import numpy as np

x = np.linspace(-10, 11, 5)

np.piecewise(x, [x < 0, ((x >= 0) & (x < 10)), x >= 10], [0, 1, 10])

We can also use the array function in numpy instead of linspace to generate a numpy array.

import numpy as np

x = np.array([-10, 2, 15])

np.piecewise(x, [x < 0, ((x >= 0) & (x < 10)), x >= 10], [0, 1, 10])

The output will be:

array([ 0,  1, 10])

The function piecewise compares each value: -10, 2, and 15 with the interval condition.

First, for the value -10, it will check the condlist. The condlist will output the value True for the first condition ‘x < 0’ and False for the rest two conditions.

As mentioned above, we will print only those values from the funclist for which the corresponding value in the condlist is True. So, the corresponding value for ‘x<0’ in funclist, which is 0, will be printed.

Similarly, for the other two values 2 and 15, 1 and 10 will be printed respectively.

Using Lambda in Numpy Piecewise

We used a list of numbers as the funclist value in the above code. But if we want to use sub-functions to output a value, we can use lambda functions.

A lambda function is an anonymous, single-line function that can have any number of arguments but only one expression. The syntax of the lambda function is:

lambda (arguments of function) : (single line expression)

Using lambda, the code would be:

import numpy as np

x = np.array([-10, 2, 15])

np.piecewise(x, [x < 0, ((x >= 0) & (x < 10)), x >= 10], [lambda x : x**2, lambda x : 10 - x, lambda x : 2*x + 3])
numpy piecewise function

We used lambda to achieve the sub functions given in the image above.

The output is:

array([100,   8,  33])

Using numpy piecewise for multi dimensional array

Instead of a one-dimensional array, we can also pass a multi-dimensional array. We will take an example where we pass a two-dimensional array to the function piecewise.

import numpy as np

x = np.array([[-10, 2], [15,100]])

np.piecewise(x, [x < 0, ((x >= 0) & (x < 10)), x >= 10], [0, 1,10])

The steps are the same, but instead of passing a 1D array, we shall be passing a 2D array to the numpy’s array function. Thus, the output will also be a two-dimensional array.

array([[ 0,  1],
       [10, 10]])

Also, Read

FAQ’s

What is the difference between numpy.where() and numpy.piecewise()

The where() function in numpy works like the conditional statement from the C language. It can return two values – x and y depending on whether the condition given is satisfied. 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.

Why does Valueerror occur while using numpy.piecewise()?

Valueerror can occur while dealing with the piecewise() function if the length of the condlist differs from the length of the funclist. The length of the funclist should be either equal to or one greater than the value of condlist. Any other scenarios would eventually raise Valueerror.


That sums up everything about Numpy Piecewise. If you have any thoughts to share or any questions in mind, let us know in the comments.

Until then, Keep Learning!

5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments