How can I lower down values to a specific number in a numpy array

Let’s say I have an array like this:

[1,5, 2, 6, 6.7, 8, 10]

I want to lower down the numbers that are larger than n.
So for example if n is 6, the array will look like this:

[1,5, 2, 6, 6, 6, 6]

I have tried a solution using numpy.vectorize:

lower_down = lambda x : min(6,x)
lower_down = numpy.vectorize(lower_down)

It works but it’s too slow. How can I make this faster? Is there a numpy function for achieving the same result?

>Solution :

Numpy already has a minimum function, no need to create your own.

>>> np.minimum(6, [1,5, 2, 6, 6.7, 8, 10])
array([1., 5., 2., 6., 6., 6., 6.])

Leave a Reply