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

Question:

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?

Asked By: Enx

||

Answers:

You could use numpy.minimum (or numpy.maximum) if you want to limit it:

>>> numpy.minimum(1, [1, 2])
array([1, 1])
>>> numpy.maximum(2, [1, 2])
array([2, 2])

If you need to limit both minimum and maximum, try numpy.clip function:

>>> np.clip([1, 2, 3, 4], 2, 3)
array([2, 2, 3, 3])

From docs:

Clip (limit) the values in an array.
Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.
Equivalent to but faster than np.minimum(a_max, np.maximum(a, a_min)).

Answered By: svfat

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.])
Answered By: Dan Getz

Try something like this:

import numpy as np

data = np.array([1,5, 2, 6, 6,7, 8, 10])

data[data >6 ] = 6
Answered By: Bruno Cavalcante

You could do this:

import numpy as np

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

array[array >= 6] = 6

new_array = array

print(new_array)

[1. 5. 2. 6. 6. 6. 6.]

Answered By: geofisue
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.