5

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. Commented Aug 13, 2011 at 6:26

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Technically, @senderle answered my question but clip is noticeably faster.
@Dex, that's because you asked the wrong question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.