To write "piecewise functions" in Python, I would usually use if (either in the form of a control flow or in the form of a ternary operator).
def spam(x): return x+1 if x>=0 else 1/(1-x)
Now, with NumPy, the mantra should avoid working with single values ββin favor of vectorization for performance. Therefore, I believe that this would be preferable: As Leon points out, the following is not true.
def eggs(x): y = np.zeros_like(x) positive = x>=0 y[positive] = x+1 y[np.logical_not(positive)] = 1/(1-x) return y
(Correct me if I missed something because, frankly, I find this very ugly.)
Now, of course, eggs will only work if x is actually a NumPy array, because otherwise x>=0 just prints one boolean that cannot be used for indexing (at least it doesn't do it right).
Is there a good way to write code that looks more like spam but works idiomatically on Numpy arrays, or should I just use vectorize(spam) ?
python arrays vectorization numpy
leftaroundabout
source share