Similar to this Matlab question, I am wondering how to truncate a numpy array by cutting off the values greater than a certain threshold value. The values of the array in question are in ascending order.
import numpy as np
a=np.linspace(1,10,num=10)
truncatevalue = 5.5
How would I produce an array that has the values of a
that are less than truncatevalue
and would only include those values? In this case, the resulting array would be
a_truncated=([1., 2., 3., 4., 5.])
Bonus: I actually have two arrays I would like to truncate based on the values in one of the arrays.
import numpy as np
a=np.linspace(1,10,num=10)
b=np.array([19, 17, 15, 14, 29, 33, 28, 4, 90, 6])
truncatevalue = 5.5
b
is an arbitrary array, I just chose some numbers for a definite example. I would like to truncate b
in the same way that a
gets truncated, so that the result would be
a_truncated=([1., 2., 3., 4., 5.])
b_truncated=([19, 17, 15, 14, 29])
I don't know if it will be as simple as just repeating what needs to be done to get a_truncated
or not, so I wanted to include it as well in case there is something different that needs to be done.
You can use boolean indexing:
>>> a = np.linspace(1, 10, num=10)
>>> truncatevalue = 5.5
>>> a_truncated = a[a < truncatevalue]
>>> a_truncated
array([ 1., 2., 3., 4., 5.])
Essentially, a < truncatevalue
returns a boolean array indicating whether or not the element of a
meets the condition. Using this boolean array to index a
returns a view of a
in which each element's index is True
.
So for the second part of your question, all you need to do is this:
>>> b = np.array([19, 17, 15, 14, 29, 33, 28, 4, 90, 6])
>>> b_truncated = b[a < truncatevalue]
>>> b_truncated
array([19, 17, 15, 14, 29])
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