Reputation: 11
i am very new to python and need to define a piecewise funtion, however, as soon as i specify more than two conditions i am greeted with "ValueError: function list and condition list must be the same".
For example, the very basic test function
def test(r):
r1=1.8
return np.piecewise(r, [(r<r1), (r==r1), (r>r1)], [0, 1, 2])
produces this error, whereas a function with only two conditions
def test(r):
r1=1.8
return np.piecewise(r, [(r<r1), (r>r1)], [0, 2])
works flawlessly. I circumvented my problem by using np.select, however, i am curious as to what my mistake is and how to resolve it. I am not sure if this of interest, but the variable "r" used in the function is going to be a scalar value, not a list or array or something complicated.
Does anyone have an idea how to resolve my problem?
Upvotes: 1
Views: 1393
Reputation: 568
you are passing a list to the function but you should pass a numpy array:
r1 = 1.8
r = numpy.arange(0, 3, 0.2)
print numpy.piecewise(r, [(r<r1), (r==r1), (r>r1)], [0, 1, 2])
# prints:
# array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 2., 2., 2., 2., 2.])
but adding
r = list(r)
print numpy.piecewise(r, [(r<r1), (r==r1), (r>r1)], [0, 1, 2])
gives the error you mention.
Upvotes: 3