Python — confused by numpy's piecewise functio

2019-08-11 01:38发布

问题:

I'm trying to implement a piecewise function in Python. Since I'm using quite a few tools from numpy, I simply import everything from it (i.e. from numpy import *). My piecewise function is defined as

LinQuad = piecewise( t, [t < 1, t >= 1], [lambda t : t, lambda t : t**2] )

which results in the error NameError: global name 't' is not defined. I don't understand why I should define t — after all, it is not necessary to define t for a simple lambda function Lin = lambda t : t. In some examples the domain of t is defined, but I don't know at which values the function LinQuad will be evaluated. What to do?

回答1:

I'm no numpy expert, but it looks to me like you're expecting piecewise to return a function that you can then use elsewhere. That's not what it does - it calculates the function result itself. You could probably write a lambda expression that would take an arbitrary domain and return your calculation on it:

LinQuad = lambda x: piecewise(x, [x < 1, x >= 1], [lambda t: t, lambda t: t**2])

I am none too sure about defining the condlist boolean arrays there - presumably that's something specific to numpy.

Or if appropriate to your situation:

def LinQuad(x):
   return piecewise(x, [x < 1, x >= 1], [lambda t: t, lambda t: t**2])


回答2:

np.piecewise requires that you define the input domain at the time you call it:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.piecewise.html

You can't really get around how the method is specified. While you can use lambda functions with it, np.piecewise does not generate a method that can then be applied against arbitrary domains.