Suppose I have a numpy array
a = np.array([1, 100, 123, -400, 85, -98])
And I want to limit each value between -100
and 90
. So basically, I want the numpy array to be like this:
a = np.array([1, 90, 90, -100, 85, -98])
I know this can be done through iterating over the numpy array, but is there any other efficient method to carry out this task?
numpy. amax() will find the max value in an array, and numpy. amin() does the same for the min value.
In python is very easy to find out maximum, minimum element and their position also. Python provides different inbuilt function. min() is used for find out minimum value in an array, max() is used for find out maximum value in an array. index() is used for finding the index of the element.
For finding the minimum element use numpy. min(“array name”) function.
Write a Python Program to Find Minimum and Maximum Value in an Array. The numpy module has min and max functions to return the minimum and maximum values in a numpy array. We use these numpy min and max functions to return the minimum and maximum values in the number and string array.
The numpy module has min and max functions to return the minimum and maximum values in a numpy array. We use these numpy min and max functions to return the minimum and maximum values in the number and string array.
To do this we have to use numpy.max (“array name”) function. For finding the minimum element use numpy.min (“array name”) function. Note: You must use numeric numbers (int or float), you can’t use string.
You can easily find the index of the max value in a 1-dimensional NumPy array. But for the 2D array, you have to use Numpy module unravel_index. It will easily find the Index of the Max and Min value.
There are several ways of doing so. First, using a numpy function as proposed by Sridhar Murali :
a = np.array([1, 100, 123, -400, 85, -98])
np.clip(a,-100,90)
Second, using numpy array comparison :
a = np.array([1, 100, 123, -400, 85, -98])
a[a>90] = 90
a[a<-100] = -100
Third, if a numpy is not required for the rest of your code, using list comprehension :
a = [1, 100, 123, -400, 85, -98]
a = [-100 if x<-100 else 90 if x>90 else x for x in a]
They all give the same result :
a = [1, 90, 90, -100, 85, -98]
As for coding style, I would prefer numpy comparison or list comprehension as they state clearly what is done, but it is up to you really. As for speed, with timeit.repeat
on 100000 repetitions, I get on average, from the best to the worst :
Clearly, if an array is not necessary afterwards, list comprehension is the way to go. And if you need an array, direct comparison is almost twice more efficient that the clip
function, while more readable.
I think the easiest way for you to get the result is using the clip function from numpy.
import numpy as np
a = np.array([1, 100, 123, -400, 85, -98])
np.clip(a,-100,90)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With