开发者

Forcing Elements in a Numpy Array to be Within a Specified Range [duplicate]

开发者 https://www.devze.com 2023-03-27 07:50 出处:网络
This question already has answers here: numpy convert number to byte (2 answers) Closed 4 years ago. I have a numpy array and I want to force every element that is less than zero to be zero
This question already has answers here: numpy convert number to byte (2 answers) Closed 4 years ago.

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 accom开发者_Python百科plish this?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消