5
votes

I have a numpy array and I want to force every element that is less than zero to be zero and every element above 255 will be forced down to 255.

eg. x = (-1,7,255,299) => (0,7,255,255)

Is there a not too complicated one-liner that can accomplish this?

1
Perhaps you should change the title of this question to more accurately reflect your specific problem. - senderle

1 Answers

8
votes

The answer is numpy.clip

numpy.clip(x, 0, 255)

Regarding the question posted in your title: don't. You can apply the lambda function to every element, using vectorize but that's rarely the best choice.