4

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.

2 Answers 2

10

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])
Sign up to request clarification or add additional context in comments.

2 Comments

Do you need a_truncated = a[a < truncatevalue]?
@Joshua - To return either a_truncated or b_truncated in your example, all you need is the boolean array a < truncatevalue. As long as a, b and truncatevalue are defined you can find either array. (You don't need to assign a_truncated to a[a < truncatevalue] first.)
-3
a_truncated = [value for value in a if value < truncateValue]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.