Is the NumPy set limited to 0 and 1?

Basically, I have an array that can change between any two numbers, and I want to save the distribution, limiting it [0,1]. The function for this is very simple. I usually write it as:

def to01(array): array -= array.min() array /= array.max() return array 

Of course, it can and should be more difficult to take into account many situations, such as all values ​​being the same (divide by zero) and swim against integer division (use np.subtract and np.divide instead of operators). But this is the most basic.

The problem is that I do this very often in the materials of my project, and it seems like a fairly standard mathematical operation. Is there a built-in function that does this in NumPy?

+5
source share
1 answer

I don’t know if there is a built-in for this (maybe not, it’s not very difficult to do as it is). You can use vectorize to apply the function to all elements of the array:

 def to01(array): a = array.min() # ignore the Runtime Warning with numpy.errstate(divide='ignore'): b = 1. /(array.max() - array.min()) if not(numpy.isfinite(b)): b = 0 return numpy.vectorize(lambda x: b * (x - a))(array) 
+1
source

Source: https://habr.com/ru/post/1202374/


All Articles