Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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?

like image 222
Dex Avatar asked Aug 12 '11 03:08

Dex


People also ask

How do you duplicate an element in an array in NumPy?

Python Numpy – Duplicate or Copy Array Copying array means, a new instance is created, and the contents of the original array is copied into this array. To copy array data to another using Python Numpy library, you can use numpy. ndarray. copy() function.

What does .all do in NumPy?

all() in Python. The numpy. all() function tests whether all array elements along the mentioned axis evaluate to True.

How do I normalize values in NumPy?

In order to normalize a vector in NumPy, we can use the np. linalg. norm() function, which returns the vector's norm value. We can then use the norm value to divide each value in the array to get the normalized array.


1 Answers

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.

like image 165
Winston Ewert Avatar answered Oct 16 '22 11:10

Winston Ewert